我看过的每一篇文章或问题都说,只需使用:
str.replace(/yourstring/g, 'whatever');
但是我想用一个变量来代替"yourstring"。然后人们说,只要使用new RegExp(yourvar, 'g')
。问题是yourvar
可能包含特殊字符,我不希望它被当作正则表达式对待。
那么我们该如何正确地做到这一点呢?
示例输入:
'a.b.'.replaceAll('.','x')
期望输出:
'axbx'
您可以进行拆分和联接。
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";
来源http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
您可以使用以下方法转义yourvar
变量:
function escapeRegExp(text) {
return text.replace(/[-[]/{}()*+?.\^$|]/g, "\$&");
}
XRegExp提供了一个用于转义字符串中正则表达式字符的函数:
var input = "$yourstring!";
var pattern = new RegExp(XRegExp.escape(input), "g");
console.log("This is $yourstring!".replace(pattern, "whatever"));
// logs "This is whatever"
解决方案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);
};
解决方案2
'a.b.c.'.split('.').join('x');
jsPerf测试