如何用`replace`方法用相应的关键字替换多个关键字? [英] How to replace multiple keywords by corresponding keywords with the `replace` method?
本文介绍了如何用`replace`方法用相应的关键字替换多个关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作一个内容可编辑的div,在其中用星号替换显式单词.这是我的JavaScript代码:
I want to make a content editable div in which I replace explicit words with asterisks. This is my JavaScript code:
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>
如您所见,我尝试使用正则表达式运算符一次替换多个字符串,但是它不起作用.它不会将 badtext2
替换为 cleantext2
,而是将 badtext1
替换为 0
.如何使单个 .replace()
语句替换多个字符串?
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 badtext2
with cleantext2
, and it replaces badtext1
with 0
. How can I make a single .replace()
statement replace multiple strings?
推荐答案
使用/.../g
表示全局替换.
var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/);
这篇关于如何用`replace`方法用相应的关键字替换多个关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文