1

I have a user-created string which is to be used as a regular expression. How can I test the validity of this string?

My first thought was to use a regular expression to test this, but, thinking about it, the regular expression syntax itself is not a regular language, so this doesn't work.

My second thought was to attempt to create a RegExp object using the string. However, the documentation does not mention what should happen when the string is an invalid regular expression.

Any other ideas?

1
  • Try using an invalid regular expressions and see what happens. Then take it from there. Commented Apr 8, 2014 at 16:16

1 Answer 1

3

Use try/catch to determine whether given string is able to create a valid RegExp object or not:

s = "(abc"; // invalid input regex string
valid = false;
try {
   new RegExp(s);
   valid = true; // reached here regex is valid
} catch(ex) {}

console.log(valid); // false
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I found the specification that describes this behavior, which is what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.