使用单词边界评估的正则表达式
我正在尝试创建一个错误的单词过滤器,该过滤器会抛出包含所提供列表中的任何单词的推文,不区分大小写。唯一的问题是我想对坏词列表进行简单的编码,以便坏词不会下载到客户端浏览器。我认为我能做到的唯一方法是评估正则表达式。唯一的问题是, eval 似乎不适用于包含 \b 的情况。如何让正则表达式 r3 和 r4 在下面工作?
// encoded bad word list decoded to below
var badwordlist = 'Sam,Jimmy,Johnny';
var restr = badwordlist.split(',').join('|');
// this works
var r2 = /\b(Sam|Jimmy|Johnny)\b/i;
var ndx2 = "safads jimmy is cool".search(r2);
// these don't
var r3 = eval('/\b('+restr+')\b/i');
var ndx3 = "safads jimmy is cool".search(r3);
var r4 = new RegExp('\b('+restr+')\b','i');
var ndx4 = "safads jimmy is cool".search(r4);
alert(restr);
alert('ndx2:'+ndx2 +',ndx3:'+ndx3 + 'ndx4:'+ ndx4 );
I'm trying to create a bad word filter that throws out tweets that contain any of the words in a provided list, case insensitive. Only problem is that I want to do a simple encoding of the bad word list so that bad words are not downloaded to the client browser. I think the only way I can do it is by eval'ing a regular expression. Only thing is, eval doesn't seem to work with the \b's included. How do I get regular expressions r3 and r4 to work below?
// encoded bad word list decoded to below
var badwordlist = 'Sam,Jimmy,Johnny';
var restr = badwordlist.split(',').join('|');
// this works
var r2 = /\b(Sam|Jimmy|Johnny)\b/i;
var ndx2 = "safads jimmy is cool".search(r2);
// these don't
var r3 = eval('/\b('+restr+')\b/i');
var ndx3 = "safads jimmy is cool".search(r3);
var r4 = new RegExp('\b('+restr+')\b','i');
var ndx4 = "safads jimmy is cool".search(r4);
alert(restr);
alert('ndx2:'+ndx2 +',ndx3:'+ndx3 + 'ndx4:'+ ndx4 );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 RegExp() 构造函数内使用双重转义:
无论何时从字符串创建正则表达式,都需要对转义字符进行转义。另外,不要使用eval()来创建正则表达式:-)
Use double-escaping inside the RegExp() constructor:
Whenever you're creating a regular expression from a string, you need to escape the escape character. Also, don't use eval() to create regular expressions :-)