如何在Javascript中替换多个单词

7

我想用javascript中的replace()方法替换文本中的几个单词,该怎么做呢?

例如,如果我想用'Jackie Chan'替换'Dave Chambers, David Chambers, Will Smith',不管它们是大写还是小写,我是否需要在同一个字符串变量上重复使用replace()方法呢?

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

请参考以下链接,其中有关于JavaScript多重替换的讨论:http://stackoverflow.com/questions/832257/javascript-multiple-replace - Anderson Green
6个回答

14

使用正则表达式的交替符(|)和不区分大小写标志(/i):

var str = sometext.innerHTML,
    reg = /Dave Chambers|David Chambers|Will Smith/i;

str = str.replace(reg, "Jackie Chan"); 

可以使用一个更短、更复杂的正则表达式:

/Dav(?:e|id) Chambers|Will Smith/i;

如果可能会有多个匹配项,则添加全局修饰符(g)来替换所有的匹配项:

/Dav(?:e|id) Chambers|Will Smith/ig;

你可以在这里了解更多关于正则表达式的内容,或者通过谷歌搜索。你可以在这里查看一个正在工作的演示。


1
同时替换每个单词为另一个不同的单词是否也有可能呢(例如,将“成龙”替换为“威尔·史密斯”,并将“威尔·史密斯”替换为“成龙”)? - Anderson Green

3

这个函数可以替换字符串中的任意单词。

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

这对我来说有效,可以替换一个或多个单词,谢谢!我从这个答案中发布了一个回答。 - emotality
谢谢,我已将其调整为以下内容 String.prototype.replaceWordRegExp = function(words, replacement) { var re = new RegExp( '\\b' + words.join('|') + '\\b','gi'); return this.replace(re, replacement); } 使用方法如下 str = str.replaceWordRegExp(['YOU\\s', 'get'], 'XXX'); 在替换中您可以使用正则表达式,只需对需要转义的字符进行双重转义即可。因此,\s 变成了 \\s - Ste

2
str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Jackie Chan');

1

如果您想忽略大小写,您需要使用正则表达式:

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

你可以像上面那样在一条语句中完成所有操作,这是我更喜欢的方式,因为它更易读。


(A) 不需要调用三次“replace”函数 (B) 正则表达式使用正斜杠进行分隔,而不是反斜杠。 - Pointy
(A) 没有理由不这样做 (B) 我明白了,打错字没有必要否定答案。 - Sparafusile

0
如果你想要进行一些数组替换,同时需要考虑像"."或","这样的分隔符,我已经创建了一些类似的东西可以帮助你。

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

vsync的回答帮助我在整个innerHTML中突出显示一个单词。这可以用于问题和许多其他事情,谢谢!

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;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接