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'
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'
Share
Improve this question
edited Aug 17, 2015 at 20:52
mpen
asked Mar 9, 2012 at 21:51
mpenmpen
283k281 gold badges889 silver badges1.3k bronze badges
3
|
5 Answers
Reset to default 9You 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";
From http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
you can escape your yourvar
variable using the following method:
function escapeRegExp(text) {
return text.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
XRegExp provides a function for escaping regular expression characters in strings:
var input = "$yourstring!";
var pattern = new RegExp(XRegExp.escape(input), "g");
console.log("This is $yourstring!".replace(pattern, "whatever"));
// logs "This is whatever"
Solution 1
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
String.prototype.replaceAll = function(search, replace) {
return this.replace(new RegExp(RegExp.escape(search),'g'), replace);
};
Solution 2
'a.b.c.'.split('.').join('x');
jsPerf Test
"ABc34*\d/4h"
you want to work with/replace? – David Thomas Commented Mar 9, 2012 at 21:53string.replace
does. – mpen Commented Mar 9, 2012 at 21:59'a.b.c'.split('.').join('x')
– david Commented Mar 9, 2012 at 22:14