I was wondering if there is a way of testing if a regular expression inputted is valid in JavaScript.
Something like
if ( isValidRegexp($("#regexp")) {
...
}
I don't need a regex like this question Regexp that matches valid regexps
I was wondering if there is a way of testing if a regular expression inputted is valid in JavaScript.
Something like
if ( isValidRegexp($("#regexp")) {
...
}
I don't need a regex like this question Regexp that matches valid regexps
You can create this function like this:
function isValidRE(str) {
var isValid=true;
try {
var re = new RegExp(str, "g");
} catch(err) {
isValid=false;
}
return isValid;
}
console.log(isValidRE("\d")); // true
console.log(isValidRE("(\d")); // false
OK, so it is pretty easy. You just create a new RegExp object and catch the error:
try{
var r = new RegExp("my regex string");
}
catch(e){
//regex is invalid
}