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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.