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?
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); } *, +, [.return to the functions. I was obviously focused on the regexp part, not the replace part.The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){ str.replace(replaceWhat,replaceTo,"g"); } https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace