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?
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.
replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With