views:

40

answers:

1

I am trying to build a javascript regex based on user input:

function FindString(input) {
    var reg = new RegExp('' + input + '');
    // [snip] perform search
}

But the regex will not work correctly when the user input contains a ? or * because they are interpreted as regex specials. In fact, if the user puts an unbalanced ( or [ in their string, the regex isn't even valid.

What is the javascript function to correctly escape all special characters for use in regex?

+2  A: 

Google led me here:

http://simonwillison.net/2006/Jan/20/escape/

Be sure to use the updated code at the bottom.

cnanney