How to replace several words in javascript

前端 未结 6 786
心在旅途
心在旅途 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条回答
  •  萌比男神i
    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," <$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 <>. Replacing, in  case. Even .",
        [ "funny", "even", "function" ],
        [ "complex", "including", "code" ]
      )
    ); // Testing the <>. Replacing, in  case. including .

提交回复
热议问题