将正则表达式修饰符选项传递给RegExp对象 [英] Passing regex modifier options to RegExp object
问题描述
我正在尝试创建与此类似的内容:
I am trying to create something similar to this:
var regexp_loc = /e/i;
除了我希望正则表达式依赖于字符串之外,因此我尝试使用新的正则表达式,但无法获得想要的东西.
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
基本上,我希望上述regexp中的e
是一个字符串变量,但是语法失败.
Basically I want the e
in the above regexp to be a string variable but I fail with the syntax.
我尝试过这样的事情:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
基本上,我想在较大的字符串中搜索子字符串,然后用其他不区分大小写的字符串替换该字符串.
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
致谢, 亚历山大
推荐答案
您需要传递第二个参数:
var r = new RegExp(keyword, "i");
您还需要转义字符串中的任何特殊字符,以防止进行正则表达式注入攻击.
You will also need to escape any special characters in the string to prevent regex injection attacks.
这篇关于将正则表达式修饰符选项传递给RegExp对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!