JS replacing all occurrences of string using variable

30,954

The RegExp constructor takes a string and creates a regular expression out of it.

function name(str,replaceWhat,replaceTo){
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}

If replaceWhat might contain characters that are special in regular expressions, you can do:

function name(str,replaceWhat,replaceTo){
    replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}

See Is there a RegExp.escape function in Javascript?

Share:
30,954
usama8800
Author by

usama8800

Updated on November 05, 2020

Comments

  • usama8800
    usama8800 over 3 years

    I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this

    function name(str,replaceWhat,replaceTo){
        str.replace(/replaceWhat/g,replaceTo);
    }
    

    How can i use a variable in the first argument?

  • pts
    pts almost 11 years
    This doesn't work as expected if replaceWhat contains regexp metacharacters, e.g. *, +, [.
  • pts
    pts almost 11 years
    This is Firefox-specific, in Chrome it replaces only the first occurrence.
  • Barmar
    Barmar almost 11 years
    @pts So does a literal regexp.
  • dc5
    dc5 almost 11 years
    Then add this logic in as well: Is there a RegExp.escape function in Javascript?
  • Hogan
    Hogan almost 11 years
    True... it had the "nonstandard" flag.
  • dronus
    dronus over 10 years
    If used like the asker intended, this will give wrong results if metacharacters appear in replaceWhat. So better chose another answer!
  • Barmar
    Barmar over 10 years
    @dronus Isn't that what pts said in his comment? dc5 pointed to a workaround for that.
  • dronus
    dronus over 10 years
    Yes, it is exactly what pts said. But that doesn't make the answer itself valid... maybe you like to edit it?
  • tjcafferkey
    tjcafferkey almost 7 years
  • thatOneGuy
    thatOneGuy about 6 years
    remember, you need to bind this to a new variable : stackoverflow.com/questions/12231644/…
  • thatOneGuy
    thatOneGuy about 6 years
    remember, you need to bind this to a new variable : stackoverflow.com/questions/12231644/…
  • Barmar
    Barmar about 6 years
    @thatOneGuy Good catch, I've added a return to the functions. I was obviously focused on the regexp part, not the replace part.
  • Freddy Daniel
    Freddy Daniel over 4 years
    @Hogan this is not working currently please remove this answer or update with working solution.