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?
For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With