我想使内容编辑的DIV中,我用星号代替明确的话。 这是我的JavaScript代码:
function censorText(){
var explicit = document.getElementById("textbox").innerHTML;
var clean = explicit.replace(/"badtext1","cleantext1"|"badtext2","cleantext2"/);
document.getElementById("textbox").innerHTML = clean;
}
下面是我的HTML contenteditable div
<div contenteditable="true" onkeyup="censorText()" id="textbox">Hello!</div>
正如你所看到的,我试图用一个正则表达式运算符一次性替换多个字符串,但它不工作。 它不会取代badtext2
与cleantext2
,它取代badtext1
与0
。 我怎样才能使一个单一的.replace()
语句替换多个字符串?
使用/.../g
指示全局替换。
var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/);
处理这个的通用方法如下:
建立一个字典,并建立一个正则表达式:
var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'g');
正则表达式是从字典中的关键字(注意它们不能包含正则表达式特殊字符)构成。
现在做一个替换,使用替换字符串替换一个函数,该函数简单地返回相应的键的值。
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/
我觉得从今朝的答案大约覆盖,但一些其他的注意事项。
1)在正则表达式,不要使用“
2)你可以匹配多个字符串,但我认为只使用一个正则表达式替换为一个值。 我能想到的来匹配多个唯一的办法是今朝已完成。
下面的代码片段似乎为我工作:
function censorText(){
var explicit = document.getElementById("textbox").innerHTML;
var clean = explicit.replace(/bad|worse/gi,"good");
document.getElementById("textbox").innerHTML = clean;
}
我发现的另一个问题是,当更换发生时,光标返回到文本框,这是会得到令人沮丧的开始。 如果我找到一个答案,我会发布。