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

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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"?)
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?"

2 Comments

This worked for me to replace one or more words, thanks! I posted an answer from this answer.
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.
2
str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Jackie Chan');

Comments

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.

2 Comments

(A) no need to call "replace" three times (B) regular expressions are delimited by forward slashes, not backslashes.
(A) no reason not to (B) I caught that, no need to neg the answer for a typo.
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;
};

Comments

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>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.