Every article or question I've seen pretty much says, just use:
str.replace(/yourstring/g, 'whatever');
But I want to use a variable in place of "yourstring". Then people say, just use new RegExp(yourvar, 'g')
. The problem with that is that yourvar
may contain special characters, and I don't want it to be treated like a regex.
So how do we do this properly?
Example input:
'a.b.'.replaceAll('.','x')
Desired output:
'axbx'
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. replaceAll() method is more straight forward.
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')
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 original string is left unchanged.
You can split and join.
var str = "this is a string this is a string this is a string";
str = str.split('this').join('that');
str; // "that is a string that is a string that is a string";
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