1

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

3
  • I dont think I have ever seen invalid Regex, are there some characters that are not valid? Commented Apr 26, 2013 at 7:43
  • Incorrectly nested brackets for example are considered to be invalid regex. Commented Apr 26, 2013 at 7:48
  • @martin: I don't know what exactly musefan had in mind, but I'm certain that depending on its contents, a FOO is either a Regex or not-a-Regex, i.e. for me, improper nesting of brackets makes not-a-Regex :) Therefore we can argue about "ever seeing invalid Regex" :)) Commented Apr 26, 2013 at 9:04

2 Answers 2

3

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

Live Demo: http://ideone.com/9z2UKW

Sign up to request clarification or add additional context in comments.

2 Comments

Chose this answer because it is a function, but what is the "g" for?
g was for global, not really needed in this case and you can omit it.
2

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
}

Here is a working example

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.