5

How can I check a JavaScript string is in a RegExp format, then convert it to RegExp?

I found a way with RegExp, but the rule is too complex to make it right.

function str2Regex(str){
  var rule = /\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/([gim]*)/;
  var match = str.match(rule);
  return match ? new RegExp(match[1],match[3]) : str;
}

Now I'm using /\/(.*)\/(?=[igm]*)([igm]*)/ which works.

4
  • Why do you need the check the validity of a regular expression? That seems like a serious issue. Commented Jan 8, 2013 at 17:07
  • I'm writing some route function, use a cfg object, which key is string or regex, value is handlerFn, because the object key must be a string, so I had to detect the key is a string or regex string, then change it to a Regex Commented Jan 9, 2013 at 3:53
  • 1
    I've seen your edit. Your solution fails on something as simple as /**/i. You really shouldn't try to guess if a string is correct as a regex, just let the browser finds it (i.e. use try/catch around new RegExp). Commented Jan 9, 2013 at 11:27
  • Another problem with your approach is that regex engines change. Supposing it's possible to find a regex validing regexes, it wouldn't be the same when new regex feature are introduced in javascript regex engines. Commented Jan 9, 2013 at 11:33

1 Answer 1

7

The simplest way, and probably the most correct, is to use try/catch :

try {
 r = new RegExp(str);
} catch(error) {
  // no good
}

You get a SyntaxError when the string doesn't match a well formed regular expression.

If you want to test a string whose value is like a compiled regular expression (for example "/\b=\b/g", you can use such a function :

function checkCompiledRegex(str) {
  if (str[0]!='/') return false;
  var i = str.lastIndexOf('/');
  if (i<=0) return false;
  try {
    new RegExp(str.slice(1, i), str.slice(i+1));
  } catch(error) {
    return false;
  }
  return true;
}
Sign up to request clarification or add additional context in comments.

4 Comments

RegExp's param seems can't use / and igm. such as: ` "y".match(new RegExp("/y/i")) ` is null.
When you build a regex from a string, remove the "/" and the modifiers. /y/i is a compiled regex.
I know RegExp("\d+","igm"), so I'm searching for a regex to extract them from string "/\d+/igm"
if the regexp has a '/', this will not pass. for example, we can use /(w+)\/(\d+)/ to detect match "a/2" , then the regex string is "/(w+)\\/(\d+)/" which can't pass your fn

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.