neolaser
neolaser

Reputation: 6907

Javascript: Convert a String to Regular Expression

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

Upvotes: 4

Views: 4281

Answers (3)

Phrogz
Phrogz

Reputation: 303261

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 :)

Upvotes: 2

Chandu
Chandu

Reputation: 82913

You can use the RegExp object:

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

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

Upvotes: 1

ChaosPandion
ChaosPandion

Reputation: 78272

You'll want to use the RegExp constructor:

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

MDC - RegExp

Upvotes: 9

Related Questions