3 回答

TA貢獻(xiàn)1848條經(jīng)驗 獲得超6個贊
這RegExp是一個很好的方向,只是你需要一些標(biāo)志(使其不i區(qū)分大小寫,并且是g局部的——所以替換所有出現(xiàn)的):
var text="Under the xxx\nUnder the XXx\nDarling it's MMM\nDown where it's mmM\nTake it from me";
console.log("Obscene:",text);
var banned=["XXX","MMM"];
banned.forEach(nastiness=>{
text=text.replace(new RegExp(nastiness,"gi"),"");
});
console.log("Okay:",text);

TA貢獻(xiàn)1895條經(jīng)驗 獲得超7個贊
通常,您應(yīng)該.toLowerCase()
在比較時使用雙方,strings
以便它們可以在邏輯上匹配。
但問題實際上是從正則表達(dá)式來你使用,你在哪里忽略大小寫,你只需要添加的i
標(biāo)志吧:
var regExp = new RegExp(banned[x], 'gi'); text = text.replace(regExp, '');
筆記:
另請注意,alert()
不建議使用in 循環(huán),您可以更改邏輯以僅在一個 中提醒所有匹配的項目alert()
。

TA貢獻(xiàn)1934條經(jīng)驗 獲得超2個贊
您實際上可以做的是將兩個變量都轉(zhuǎn)換為全部大寫或全部小寫。
if (text.toLowerCase().includes(banned[x].toLowerCase())) {
alert(banned[x] + ' is not allowed!');
}
未經(jīng)測試,但它應(yīng)該可以工作。無需使用,search因為無論如何您都不需要索引。使用includes更干凈。
添加回答
舉報