Javascript: Convert a String to Regular Expression
I want to convert a string tha开发者_StackOverflowt 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:
- 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 :)
You can use the RegExp object:
var extList = ['jpg','gif','jpg'];
var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$");
精彩评论