str = str.replace(/abc/g, '');
In response to comment:
(回应评论:)
var find = 'abc';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
In response to Click Upvote 's comment, you could simplify it even more:
(为了响应Click Upvote的评论,您可以进一步简化它:)
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find
function above without pre-processing it to escape those characters.
(注意:正则表达式包含特殊的(元)字符,因此危险地在上面的find
函数中盲目传递参数,而无需对其进行预处理以转义那些字符。)
This is covered in the Mozilla Developer Network 's JavaScript Guide on Regular Expressions , where they present the following utility function: (Mozilla开发人员网络的JavaScript正则表达式指南中对此进行了介绍,该指南提供了以下实用程序功能:)
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|[]/\])/g, "\$1");
}
So in order to make the replaceAll()
function above safer, it could be modified to the following if you also include escapeRegExp
:
(因此,为了使上面的replaceAll()
函数更安全,如果还包含escapeRegExp
,则可以将其修改为以下escapeRegExp
:)
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…