How to replace several words in javascript

前端 未结 6 774
心在旅途
心在旅途 2020-12-06 07:43

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,

相关标签:
6条回答
  • 2020-12-06 08:02
    str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Jackie Chan');
    
    0 讨论(0)
  • 2020-12-06 08:05

    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;
    };
    
    0 讨论(0)
  • 2020-12-06 08:09

    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.

    0 讨论(0)
  • 2020-12-06 08:09

    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.

    0 讨论(0)
  • 2020-12-06 08:12

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

    0 讨论(0)
  • 2020-12-06 08:24

    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?"
    
    0 讨论(0)
提交回复
热议问题