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?
Author by
usama8800
Updated on November 05, 2020Comments
-
usama8800 over 3 years
I know that
str.replace(/x/g, "y")
replaces all x's in the string but I want to do thisfunction name(str,replaceWhat,replaceTo){ str.replace(/replaceWhat/g,replaceTo); }
How can i use a variable in the first argument?
-
pts almost 11 yearsThis doesn't work as expected if replaceWhat contains regexp metacharacters, e.g.
*
,+
,[
. -
pts almost 11 yearsThis is Firefox-specific, in Chrome it replaces only the first occurrence.
-
Barmar almost 11 years@pts So does a literal regexp.
-
dc5 almost 11 yearsThen add this logic in as well: Is there a RegExp.escape function in Javascript?
-
Hogan almost 11 yearsTrue... it had the "nonstandard" flag.
-
dronus over 10 yearsIf used like the asker intended, this will give wrong results if metacharacters appear in replaceWhat. So better chose another answer!
-
Barmar over 10 years@dronus Isn't that what pts said in his comment? dc5 pointed to a workaround for that.
-
dronus over 10 yearsYes, it is exactly what pts said. But that doesn't make the answer itself valid... maybe you like to edit it?
-
tjcafferkey almost 7 years
-
thatOneGuy about 6 yearsremember, you need to bind this to a new variable : stackoverflow.com/questions/12231644/…
-
thatOneGuy about 6 yearsremember, you need to bind this to a new variable : stackoverflow.com/questions/12231644/…
-
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 over 4 years@Hogan this is not working currently please remove this answer or update with working solution.