Javascript 将正则表达式修饰符选项传递给 RegExp 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5172183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing regex modifier options to RegExp object
提问by Alexander
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 依赖于一个字符串,所以我尝试使用新的 RegExp 但我无法得到我想要的。
Basically I want the e
in the above regexp to be a string variable but I fail with the syntax.
基本上我希望e
上面的正则表达式是一个字符串变量,但我的语法失败了。
I tried something like this:
我试过这样的事情:
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
问候,亚历山大
回答by SLaks
You need to pass the second parameter:
您需要传递第二个参数:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
您还需要转义字符串中的任何特殊字符以防止正则表达式注入攻击。
回答by Ric
You should also remember to watch out for escape characters within a string...
您还应该记住注意字符串中的转义字符...
For example if you wished to detect for a single number \d{1} and you did this...
例如,如果您希望检测单个数字 \d{1} 并且您这样做了...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
这会失败,因为初始 \ 是转义字符,您需要“转义”,就像这样......
var pattern = "\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
回答by James Sulak
回答by liudaxingtx
Want to share an example here:
想在这里分享一个例子:
I want to replace a string like: hi[var1][var2]
to hi[newVar][var2]
.
and var1
are dynamic generated in the page.
我想替换一个字符串,如:hi[var1][var2]
to hi[newVar][var2]
。并且var1
是在页面中动态生成的。
so I had to use:
所以我不得不使用:
var regex = new RegExp("\\["+var1+"\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me. The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
这对我来说很好用。以防有人像我一样需要这个。我必须使用 [] 的原因是 var1 本身可能是一个非常简单的模式,添加 [] 会更准确。
回答by Alireza
You need to convert RegExp, you actually can create a simple function to do it for you:
您需要转换RegExp,您实际上可以创建一个简单的函数来为您执行此操作:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
并称之为:
toReg("something")
回答by Harshal Khatri
var keyword = "something";
var 关键字 = "东西";
var test_regexp = new RegExp(something,"i");