javascript 如何替换javascript中的几个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4784595/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace several words in javascript
提问by Shaoz
I wanna replace several words in a text using replace()in javascript, how can I do that?
我想用replace()javascript替换文本中的几个单词,我该怎么做?
For example, if I wanna replace, 'Dave Chambers, David Chambers, Will Smith' with 'Hymanie 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.
例如,如果我想用“成龙”替换“戴夫·钱伯斯”、“大卫·钱伯斯”、“威尔·史密斯” ,无论它们是大写还是小写,我是否必须不断重复相同的方法?字符串变量每次,即replace()
var str = sometext.innerHTML;
str.replace('Dave Chambers', 'Hymanie Chan');
str.replace('David Chambers', 'Hymanie Chan');
str.replace('Will Smith', 'Hymanie Chan');
回答by Andy E
Use a regular expression with the alternator (|) and case insensitive modifier (/i):
使用带有交流发电机 ( |) 和不区分大小写的修饰符 ( /i)的正则表达式:
var str = sometext.innerHTML,
    reg = /Dave Chambers|David Chambers|Will Smith/i;
str = str.replace(reg, "Hymanie 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: 
如果可能出现超过 1 次,请添加全局修饰符 ( g) 以替换所有:
/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.
回答by Pointy
str.replace(/(Dav(e|id) Chambers)|(Will Smith)/ig, 'Hymanie Chan');
回答by vsync
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?"
回答by Sparafusile
You'll want to use regular expressions if you want to ignore case:
如果您想忽略大小写,您将需要使用正则表达式:
var str = sometext.innerHTML;
str.replace(/Dave Chambers/ig, 'Hymanie Chan')
   .replace(/David Chambers/ig, 'Hymanie Chan')
   .replace(/Will Smith/ig, 'Hymanie Chan');
You can do it all in one statement like above and that's how I would prefer as it's more readable.
您可以在上面的一个语句中完成所有操作,这是我更喜欢的方式,因为它更具可读性。
回答by emotality
vsync's answerhelped me to highlight a word in whole innerHTML. This could be used for the question and for many other things, thanks!
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;
};
回答by Thiago Mata
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," <> ").
    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>.
