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');
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.
This function will replace any words you want in a string.
function wordInString(s, words, replacement){
var re = new RegExp( '\\b' + words.join('|') + '\\b','gi');
return s.replace(re, replacement);
}
// usage:
var str = 'did you, or did you not, get why?';
str = wordInString(str, ['YOU', 'get'], 'XXX');
console.log(str); // "did XXX, or did XXX not, XXX why?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With