How to check if the input string is a valid Regular expression?

How do you check, in JavaScript, if a string is a proper regular expression that will compile?

For example, when you execute the following javascript, it produces an error.

var regex = new RegExp('abc ([a-z]+) ([a-z]+))');
// produces:
// Uncaught SyntaxError: Invalid regular expression: /abc ([a-z]+) ([a-z]+))/: Unmatched ')'

How does one determine if a string will be a valid regex or not?


Solution 1:

You can use try/catch and the RegExp constructor:

var isValid = true;
try {
    new RegExp("the_regex_to_test_goes_here");
} catch(e) {
    isValid = false;
}

if(!isValid) alert("Invalid regular expression");

Solution 2:

Here is a little function that checks the validity of both types of regexes, strings or patterns:

function validateRegex(pattern) {
    var parts = pattern.split('/'),
        regex = pattern,
        options = "";
    if (parts.length > 1) {
        regex = parts[1];
        options = parts[2];
    }
    try {
        new RegExp(regex, options);
        return true;
    }
    catch(e) {
        return false;
    }
}

The user will be able to test both test and /test/g for example. Here is a working fiddle.