skip to Main Content

Hi there and thank you for your help in advance.

I’m looking for some help with using a variable to dynamically replace a name in some text. I’m really stuck with this and would appreciate any help.

So far i’ve tried:

var name = 'Page2of4Sandor-0607231529Tyrell'
                var t = "Sandor"

                var prt1 = "/Page.of." + t + "gi"
                
                var reggy = new RegExp(prt1)
                console.log(name.replace(reggy, ''))

This seemed like sensible approach as

.replace(/Page.of.Sandor/gi, '')

Works just fine.
Any help appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    Spent a little more time on and found this to work:

    var text = 'Page1of4Sandor-0607231529Tyrell'
                    var fullName = 'Sandor'
    
                    var reggy = new RegExp(`Page(.|..)of(.|..)${fullName}`, 'gi')
                    console.log(text.replace(reggy, ''))


  2. You could create a function (factory) that initializes a regular expression and returns a reusable function.

    const PagingTrimmer = (title) => {
      const expression = new RegExp(`Page\d+of\d+${title}-`, 'gi');
      return (text) => text.replace(expression, '');
    };
    
    const pagingTrimmer = PagingTrimmer('Sandor'); // Instance (function)
    
    const name = 'Page2of4Sandor-0607231529Tyrell';
    const trimmed = pagingTrimmer(name);
    
    console.log(trimmed); // 0607231529Tyrell

    Here is it is thunk form. This can also be referred to as "currying".

    const PagingTrimmer = (title) => {
      const expression = new RegExp(`Page\d+of\d+${title}-`, 'gi');
      return (text) => text.replace(expression, '');
    };
    
    const name = 'Page2of4Sandor-0607231529Tyrell';
    
    const trimmed = PagingTrimmer('Sandor')(name); // Thunk or currying
    
    console.log(trimmed); // 0607231529Tyrell
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search