javascript create case insensitive regex from string

ⅰ亾dé卋堺 提交于 2020-01-04 15:50:37

问题


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. Does anyone have any suggestions?


回答1:


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

so it would be

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

See MDN for more info



来源:https://stackoverflow.com/questions/20533458/javascript-create-case-insensitive-regex-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!