2

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 );
dishwasher
  • 23
  • 2

1 Answers1

1

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
  • 338,112
  • 86
  • 474
  • 445
  • 1
    Ahhhh!!! yes!! worked! relatively new with JS so I'm only now starting to realize how bad exactly eval is! Thanks! – dishwasher Aug 20 '10 at 16:12
  • one needs to be [exceedingly careful](http://stackoverflow.com/questions/4213800/is-there-something-like-a-counter-variable-in-regular-expression-replace/4214173#4214173) when using `\b` style word boundaries in regexes. – tchrist Nov 18 '10 at 16:20
  • @tchrist: I think you're comment should be directed to the OP, I was merely answering the question :-) – Andy E Nov 18 '10 at 16:32