Passing regex modifier options to RegExp object

You need to pass the second parameter:

var r = new RegExp(keyword, "i");

You will also need to escape any special characters in the string to prevent regex injection attacks.


You should also remember to watch out for escape characters within a string...

For example if you wished to detect for a single number \d{1} and you did this...

var pattern = "\d{1}";
var re = new RegExp(pattern);

re.exec("1"); // fail! :(

that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...

var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);

re.exec("1"); // success! :D

When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:

new RegExp(keyword, "i");

Note that you pass in the flags in the second parameter. See here for more info.