Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 603
Shaoz Avatar asked Jan 24 '11 16:01

Shaoz


2 Answers

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.

like image 73
Andy E Avatar answered Sep 20 '22 13:09

Andy E


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?"
like image 33
vsync Avatar answered Sep 21 '22 13:09

vsync