如何用“replace”方法用相应的关键字替换多个关键字

How to replace multiple keywords by corresponding keywords with the `replace` method?

本文关键字:关键字 替换 何用 replace 方法      更新时间:2023-09-26

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

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

这是我的<div contenteditable>的HTML:

<div contenteditable="true" onkeyup="censorText()" id="textbox">Hello!</div>

正如您所看到的,我尝试使用regex操作符一次替换多个字符串,但它不起作用。它不是用cleantext2代替badtext2,而是用0代替badtext1。我如何使单个.replace()语句取代多个字符串?

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

var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/);

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

建立一个字典并构建一个regexp:

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

regexp由字典关键字构造(注意它们不能包含regexp特殊字符)。

现在做一个替换,在替换字符串的地方使用一个函数,该函数只是返回相应键的值。

  text = text.replace (regexp, function (_, word) { return dictionary[word]; });

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

参见提琴:http://jsfiddle.net/nJNq2/

我认为Jinzhao的回答涵盖了它,但还有一些其他的注意事项。
1)在正则表达式
中不要使用"2)你可以匹配多个字符串,但我认为只有替换为一个值使用单个RegEx。我能想到的唯一匹配多重的方法就是像金照那样。

下面的代码片段似乎对我有用:

function censorText(){             
    var explicit = document.getElementById("textbox").innerHTML;
    var clean = explicit.replace(/bad|worse/gi,"good");
     document.getElementById("textbox").innerHTML = clean;
}

我发现的另一个问题是,当替换发生时,它将光标返回到文本框的开始,这将令人沮丧。如果我找到了答案,我会贴出来的