Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

javascript - 如何替换所有出现的字符串?(How to replace all occurrences of a string?)

I have this string:

(我有这个字符串:)

"Test abc test test abc test test test abc test test abc"

Doing:

(正在做:)

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above.

(似乎只删除上面字符串中的abc第一次出现。)

How can I replace all occurrences of it?

(如何替换所有出现的内容?)

  ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...