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'
5 Answers 5
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";
1 Comment
From http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
Comments
you can escape your yourvar variable using the following method:
function escapeRegExp(text) {
return text.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
1 Comment
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"
1 Comment
nativ.replace.call(str, /[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); Library does look neat though.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');
"ABc34*\d/4h"you want to work with/replace?string.replacedoes.'a.b.c'.split('.').join('x')