使用单词边界评估的正则表达式

发布于 2024-09-15 19:22:16 字数 679 浏览 0 评论 0原文

我正在尝试创建一个错误的单词过滤器,该过滤器会抛出包含所提供列表中的任何单词的推文,不区分大小写。唯一的问题是我想对坏词列表进行简单的编码,以便坏词不会下载到客户端浏览器。我认为我能做到的唯一方法是评估正则表达式。唯一的问题是, 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就此别过 2024-09-22 19:22:16

RegExp() 构造函数内使用双重转义:

var r4 = new RegExp('\\b('+restr+')\\b','i');

无论何时从字符串创建正则表达式,都需要对转义字符进行转义。另外,不要使用eval()来创建正则表达式:-)

Use double-escaping inside the RegExp() constructor:

var r4 = new RegExp('\\b('+restr+')\\b','i');

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 :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文