Advertisement
Advertisement


Escape string for use in Javascript regex


Question

Possible Duplicate:
Is there a RegExp.escape function in Javascript?

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?

2017/05/23
1
526
5/23/2017 11:55:03 AM


Source: https://stackoverflow.com/questions/3446170
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]