0

I have the following function, but my string is never replaced? What am I doing wrong?

function customRegex(){
      return function(myString,replacement,myValue){
        var s = myString;
        var rgx = new RegExp("/("+replacement+")/,gi");
        myString = myString.replace(rgx, myValue);
        return myString;
    }
  }

  var reg = customRegex();
  console.log( reg("This is the worst!","worst","best"));
  //This is always returning the original string?
Mark
  • 4,773
  • 8
  • 53
  • 91

1 Answers1

1

There is a problem with the regex declaration. You seem to have tried adding regex delimiters, but RegExp constructor accepts a string when you build a dynamic pattern, so, the / are treated as literal symbols in the string pattern. The regex modifiers gi should be passed as a second string argument.

Use

var rgx = new RegExp(replacement,"gi");

See the demo below:

function customRegex(){
      return function(myString,replacement,myValue){
        var s = myString;
        var rgx = new RegExp(replacement,"gi");
        myString = myString.replace(rgx, myValue);
        return myString;
    }
  }

  var reg = customRegex();
  console.log( reg("This is the worst!","worst","best"));

Also, if your search pattern can contain special regex metacharacters, you will need to escape them. See Is there a RegExp.escape function in Javascript? SO thread.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563