views:

27

answers:

1

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

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

Andy E
Ahhhh!!! yes!! worked! relatively new with JS so I'm only now starting to realize how bad exactly eval is! Thanks!
dishwasher