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