4

I want to convert a string that looks like a regular expression...into a regular expression.

The reason I want to do this is because I am dynamically building a list of keywords to be used in a regular expression. For example, with file extensions I would be supplying a list of acceptable extensions that I want to include in the regex.

var extList = ['jpg','gif','jpg'];

var exp = /^.*\.(extList)$/;

Thanks, any help is appreciated

3 Answers 3

9

You'll want to use the RegExp constructor:

var extList = ['jpg','gif','jpg'];    
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');

MDC - RegExp

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

3 Comments

Another way can be to use eval(...), but creating Regexp object is far way better solution.
a) RegExp, not Regexp; b) You created /^.*.(jpg|gif|jpg)$/ (note the missing backslash); c) The third parameter is optional if you aren't going to pass any flags.
I noticed that this method does't accept regex's that start and end with a slash, ie "/^b/". is there a way to account for this besides manually trimming the slashes. (The string coms from user input).
2
var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );

Note that:

  • You need to double-escape backslashes (once for the string, once for the regexp)
  • You can supply flags to the regex (such as case-insensitive) as strings
  • You don't need to anchor your particular regex to the start of the string, right?
  • I turned your parens into a non-capturing group, (?:...), under the assumption that you don't need to capture what the extension is.

Oh, and your original list of extensions contains 'jpg' twice :)

Comments

1

You can use the RegExp object:

var extList = ['jpg','gif','jpg'];

var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$"); 

Comments

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.