Javascript 如何用 .replace() 方法替换多个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14013223/
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 multiple strings with the .replace() Method?
提问by Shrey Gupta
I want to make a content editable div in which I replace explicit words with asterisks. This is my JavaScript code:
我想制作一个内容可编辑的 div,其中我用星号替换了明确的单词。这是我的 JavaScript 代码:
function censorText(){
var explicit = document.getElementById("textbox").innerHTML;
var clean = explicit.replace(/"badtext1","cleantext1"|"badtext2","cleantext2"/);
document.getElementById("textbox").innerHTML = clean;
}
Here's the HTML for my contenteditable div
这是我的 HTML contenteditable div
<div contenteditable="true" onkeyup="censorText()" id="textbox">Hello!</div>
As you can see, I tried using a regex operator to replace multiple strings at once, but it doesn't work. It doesn't replace badtext2with cleantext2, and it replaces badtext1with 0. How can I make a single .replace()statement replace multiple strings?
如您所见,我尝试使用正则表达式运算符一次替换多个字符串,但它不起作用。它不会替换badtext2为cleantext2,而是替换badtext1为0。如何让单个.replace()语句替换多个字符串?
回答by coderLMN
use /.../gto indicate a global replace.
用于/.../g表示全局替换。
var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/);
回答by HBP
A generic way to handle this is as follows:
处理此问题的通用方法如下:
Establish a dictionary and build a regexp:
建立字典并构建正则表达式:
var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
regexp = RegExp ('\b(' + Object.keys (dictionary).join ('|') + ')\b', 'g');
The regexp is constructed from the dictionary key words (note they must not contain RegExp special characters).
regexp 是根据字典关键字构造的(注意它们不能包含 RegExp 特殊字符)。
Now do a replace, using a function in the place of the replacing string, the function simply return the value of the corresponding key.
现在做一个替换,使用一个函数代替替换字符串,该函数简单地返回对应键的值。
text = text.replace (regexp, function (_, word) { return dictionary[word]; });
The OP made no reference to upper/lower case. The following caters for initial and all caps and wraps the code as a function :
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 _;
});
}
See the fiddle : http://jsfiddle.net/nJNq2/
见小提琴:http: //jsfiddle.net/nJNq2/
回答by JonRed
I think the answer from Jinzhao about covers it, but some other notes.
1) Don't use " in the RegEx
2) You can match multiple strings, but I think only replace to one value using a single RegEx. The only way I can think of to match multiple is as Jinzhao has done.
我认为金照的答案涵盖了它,但还有一些其他说明。
1)不要在正则表达式中使用“
2)可以匹配多个字符串,但我认为只能使用单个正则表达式替换为一个值。我能想到的匹配多个的唯一方法是金照所做的。
The following code snippet seems to work for me:
以下代码片段似乎对我有用:
function censorText(){
var explicit = document.getElementById("textbox").innerHTML;
var clean = explicit.replace(/bad|worse/gi,"good");
document.getElementById("textbox").innerHTML = clean;
}
The other issue I'm finding is that when a replace happens, it returns the cursor to the start of the text box, which is going to get frustrating. If I find an answer to that, I'll post.
我发现的另一个问题是,当发生替换时,它会将光标返回到文本框的开头,这会令人沮丧。如果我找到答案,我会发布。

