用于替换字符串中的脏话的正则表达式
我正在尝试替换文本字符串中的一组单词。现在我有一个循环,它的性能不佳:
function clearProfanity(s) {
var profanity = ['ass', 'bottom', 'damn', 'shit'];
for (var i=0; i < profanity.length; i++) {
s = s.replace(profanity[i], "###!");
}
return s;
}
我想要一些运行速度更快的东西,以及用与原始单词长度相同的 ###!
标记替换坏单词的东西。
I'm trying to replace a set of words in a text string. Now I have a loop, which does not perform well:
function clearProfanity(s) {
var profanity = ['ass', 'bottom', 'damn', 'shit'];
for (var i=0; i < profanity.length; i++) {
s = s.replace(profanity[i], "###!");
}
return s;
}
I want something that works faster, and something that will replace the bad word with a ###!
mark having the same length as the original word.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法:
为了完整起见:这是一种更简单的方法,考虑到单词边界:
Here's one way to do it:
To be complete: here's a simpler way to do it, taking word boundaries into account:
看看它的工作原理:
http://jsfiddle.net/osher/ZnJ5S/3/
基本上是
:如果 PROFANITY 数组作为字符串启动会更好,或者直接作为正则表达式启动更好:
See it working:
http://jsfiddle.net/osher/ZnJ5S/3/
Which basically is:
It would be better if the
PROFANITY
array would be initiated as a string, or better - directly as a Regular Expression: