Reputation: 6907
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
Reputation: 303261
var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );
Note that:
(?:...)
, 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
Reputation: 82913
You can use the RegExp object:
var extList = ['jpg','gif','jpg'];
var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$");
Upvotes: 1
Reputation: 78272
You'll want to use the RegExp constructor:
var extList = ['jpg','gif','jpg'];
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');
Upvotes: 9