7

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');
Shaoz
  • 10,573
  • 26
  • 72
  • 100

6 Answers6

14

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.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 1
    Would it also be possible to replace each word with a different word at the same time (e. g., replacing "Jackie Chan" with "Will Smith", and replacing "Will Smith" with "Jackie Chan"?) – Anderson Green Mar 24 '13 at 20:46
3

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?"
vsync
  • 118,978
  • 58
  • 307
  • 400
  • This worked for me to replace one or more words, thanks! I posted an answer from this answer. – emotality Jul 05 '15 at 18:12
  • Thanks, I've tweaked it to this `String.prototype.replaceWordRegExp = function(words, replacement) { var re = new RegExp( '\\b' + words.join('|') + '\\b','gi'); return this.replace(re, replacement); }` and the usage would be `str = str.replaceWordRegExp(['YOU\\s', 'get'], 'XXX');` You can use regexp here in the replace only you have to double escape those that need escaping. So `\s` becomes `\\s`. – Ste Nov 26 '19 at 21:13
2
str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Jackie Chan');
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

You'll want to use regular expressions if you want to ignore case:

var str = sometext.innerHTML;
str.replace(/Dave Chambers/ig, 'Jackie Chan')
   .replace(/David Chambers/ig, 'Jackie Chan')
   .replace(/Will Smith/ig, 'Jackie Chan');

You can do it all in one statement like above and that's how I would prefer as it's more readable.

Sparafusile
  • 4,696
  • 7
  • 34
  • 57
0

vsync's answer helped me to highlight a word in whole innerHTML. This could be used for the question and for many other things, thanks!

function highlightWord(word) {
    // get your current div content by id
    var string = document.getElementById('your-id').innerHTML;

    // set word to highlight
    var newWord = '<mark>' + word + '</mark>';

    // do replacement with regular expression
    var allWords = new RegExp( '\\b' + word + '\\b','gi');
    var newString = string.replace(allWords, newWord);

    // set your new div content by id
    document.getElementById('your-id').innerHTML = newString;
};
Community
  • 1
  • 1
emotality
  • 12,795
  • 4
  • 39
  • 60
0

If you want to make some array to array replace, respecting the separators like "." or ",", I have created something like that that may help you.

function arrayReplace( text, arrFrom, arrTo, caseSensitive ) {
  return text.
    replace(/</g," <<").
    replace(/>/g,">> ").
    replace(/([\.\;\,])/g," <$1> ").
    split(" ").
    map(
      function(value) {
        var pos = arrFrom.indexOf( caseSensitive ? value : value.toLowerCase() );
        if( pos == -1 ) {
          return value;
        } else {
          return arrTo[pos % arrTo.length];
        }
      }
    ).
    join(" ").
    replace(/( \<|\> )/g,"");
};

console.log( 
  arrayReplace(
    "First example. Trivial case",
    [ "example", "case"],
    [ "demo", "test" ]
  )
); // First demo. Trivial test

console.log( 
  arrayReplace(
    "Leaving earth, passing close to the sun, going to the moon.",
    [ "earth", "sun", "moon"],
    [ "EARTH", "SUN", "MOON"]
  )
); // Leaving EARTH, passing close to the SUN, going to the MOON.

console.log( 
  arrayReplace(
    "Leaving earth, passing close to the sun, going to the moon.",
    [ "earth", "sun", "moon"],
    [ "PLANET"]
  )
); // Leaving PLANET, passing close to the PLANET, going to the PLANET.

console.log( 
  arrayReplace(
    "Leaving earth, passing close to the sun, going to the moon.",
    [ "earth", "sun", "moon"],
    [ "PLANET", "STAR" ]
  )
); // Leaving PLANET, passing close to the STAR, going to the PLANET.

console.log( 
  arrayReplace(
    "Rain rain, goes away, no one wants you any way.",
    [ "rain", "a"],
    [ "pig", "x"]
  )
);
// pig pig, goes away, no one wants you any way.

console.log( 
  arrayReplace(
    "Testing the <<function>>. Replacing, in <any> case. Even <the ;funny; ones>.",
    [ "funny", "even", "function" ],
    [ "complex", "including", "code" ]
  )
); // Testing the <<code>>. Replacing, in <any> case. including <the ;complex; ones>.
Thiago Mata
  • 2,825
  • 33
  • 32