来自字符串的javascript new regexp [英] javascript new regexp from string
问题描述
我正在尝试创建与此类似的东西:
I am trying to create something similar to this:
var regexp_loc = /e/i;
除了我希望regexp依赖于字符串,所以我尝试使用新的RegExp但是我无法得到我想要的东西。
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.
问候,
亚历山大
regards, alexander
推荐答案
您需要传递第二个参数:
var r = new RegExp(keyword, "i");
您还需要转义字符串中的任何特殊字符以防止正则表达式注入攻击。
You will also need to escape any special characters in the string to prevent regex injection attacks.
这篇关于来自字符串的javascript new regexp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!