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
799 views
in Technique[技术] by (71.8m points)

string - How to replace several words in javascript

I wanna replace several words in a text using replace() in javascript, how can I do that?

For example, if I wanna replace, 'Dave Chambers, David Chambers, Will Smith' with 'Jackie Chan', no matter if they're in upper-case or lower-case, do I have to keep repeating the replace() method on the same string variable everytime, i.e.

var str = sometext.innerHTML;
str.replace('Dave Chambers', 'Jackie Chan');
str.replace('David Chambers', 'Jackie Chan');
str.replace('Will Smith', 'Jackie Chan');
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use a regular expression with the alternator (|) and case insensitive modifier (/i):

var str = sometext.innerHTML,
    reg = /Dave Chambers|David Chambers|Will Smith/i;

str = str.replace(reg, "Jackie Chan"); 

A shorter, more complex regex could be:

/Dav(?:e|id) Chambers|Will Smith/i;

And if there may be more than 1 occurrence, add the global modifier (g) to replace all:

/Dav(?:e|id) Chambers|Will Smith/ig;

You can learn more about regular expressions here, or by searching Google. You can see a working demo here.


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

1.4m articles

1.4m replys

5 comments

56.8k users

...