[英]Regex Javascript use variable within pattern
I know that this's been asked before but none of the suggested solutions worked for me. 我知道以前曾有人问过这个问题,但没有建议的解决方案对我有用。 I've got the following:
我有以下几点:
var regex = new RegExp(/D0030001 IN/gi);
$("p").filter(function () {
return regex.test(this.id);
}).css("background-color","blue");
This one works fine. 这个很好用。 However, when I try to do
但是,当我尝试做
spl = [];
spl[0] = "D0030001";
spl[1] = "IN";
var regex = new RegExp("/" + spl[0] + " " + spl[1] + "/gi");
$("p").filter(function () {
return regex.test(this.id);
}).css("background-color","blue");
This one doesn't work. 这是行不通的。 In other words I need to use variables to construct the regex pattern.
换句话说,我需要使用变量来构造正则表达式模式。 Thanks
谢谢
您需要使用RegExp构造函数的第二个参数来设置标志,并且不需要/ /
分隔符。
var regex = new RegExp(spl[0] + " " + spl[1], "gi");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.