Mark
Mark

Reputation: 4883

Javascript Regex String Replace Not Replacing

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?

Upvotes: 0

Views: 85

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

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.

Upvotes: 1

Related Questions