如何用.replace()方法替换多个字符串?

Shr*_*pta 17 html javascript regex string replace

我想创建一个内容可编辑的div,我用星号替换显式单词.这是我的JavaScript代码:

function censorText(){
    var explicit = document.getElementById("textbox").innerHTML;
    var clean = explicit.replace(/"badtext1","cleantext1"|"badtext2","cleantext2"/);
    document.getElementById("textbox").innerHTML = clean;
}
Run Code Online (Sandbox Code Playgroud)

这是我的HTML contenteditable div

<div contenteditable="true" onkeyup="censorText()" id="textbox">Hello!</div>
Run Code Online (Sandbox Code Playgroud)

如您所见,我尝试使用正则表达式运算符一次替换多个字符串,但它不起作用.它不会取代badtext2cleantext2,它取代badtext10.如何使单个.replace()语句替换多个字符串?

cod*_*LMN 24

用于/.../g表示全局替换.

var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/);
Run Code Online (Sandbox Code Playgroud)


HBP*_*HBP 9

处理此问题的一般方法如下:

建立一个字典并构建一个正则表达式:

  var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
      regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'g');
Run Code Online (Sandbox Code Playgroud)

正则表达式是由字典关键字构成的(注意它们不能包含RegExp特殊字符).

现在进行替换,使用替换字符串的函数,函数只返回相应键的值.

  text = text.replace (regexp, function (_, word) { return dictionary[word]; });
Run Code Online (Sandbox Code Playgroud)

OP没有提及大/小写.以下内容适用于初始和全部大写,并将代码包装为函数:

  function clean (text) {
    var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
        regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'ig');

    return text.replace (regexp, function (_, word) { 
      _ = dictionary[word.toLowerCase ()];
      if (/^[A-Z][a-z]/.test (word)) // initial caps
        _ = _.slice (0,1).toUpperCase () + _.slice (1);
      else if (/^[A-Z][A-Z]/.test (word)) // all caps
        _ = _.toUpperCase ();
      return _;
    });
  }
Run Code Online (Sandbox Code Playgroud)

看小提琴:http://jsfiddle.net/nJNq2/