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
You'll want to use the RegExp constructor:
var extList = ['jpg','gif','jpg'];
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');
MDC - RegExp
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With