简体   繁体   English

javascript从字符串创建不区分大小写的正则表达式

[英]javascript create case insensitive regex from string

I am trying to do validations by matching inputs to regexes in a case insensitive way. 我试图通过以不区分大小写的方式匹配输入到正则表达式来进行验证。 The regex comes down from service as a string on an object. 正则表达式作为对象上的字符串从服务中下来。 I might get something like: 我可能得到类似的东西:

{regex:"ane"}

I can do the following: 我可以做以下事情:

var rx = new RegExp(object.regex);  /*The regex is now: /ane/*/
"plane".match(rx);

However, I what I really want to do is the following: 但是,我真正想做的是以下内容:

var rxInsensitive = new RegExp(/ane/i);  /*The regex is now: /ane/i */
"plANE".match(rx);

I am having problems converting the string to this form however. 我在将字符串转换为此表单时遇到问题。 When I do the following: 当我执行以下操作时:

var rxInsensitive = newRegExp(object.regex + "/i");

I end up getting the regex /ane/i/ instead of /ane/i . 我最终获得正则表达式/ane/i/而不是/ane/i Does anyone have any suggestions? 有没有人有什么建议?

var re = new RegExp("pattern", "flags");

so it would be 所以它会

var rx = new RegExp(object.regex,"i");

See MDN for more info 有关详细信息,请参阅MDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM