Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  146] [ 2]  / answers: 1 / hits: 20970  / 14 Years ago, mon, january 24, 2011, 12:00:00

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');

More From » string

 Answers
31

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.


[#94077] Friday, January 21, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;