[英]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 谢谢,任何帮助表示赞赏
You'll want to use the RegExp constructor: 您将要使用RegExp构造函数:
var extList = ['jpg','gif','jpg'];
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');
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 :) 哦,你原来的扩展名列表包含'jpg'两次:)
You can use the RegExp object: 您可以使用RegExp对象:
var extList = ['jpg','gif','jpg'];
var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.