gpt4 book ai didi

javascript - 正则表达式 Javascript 在模式中使用变量

转载 作者:行者123 更新时间:2023-12-02 16:44:09 26 4
gpt4 key购买 nike

我知道以前有人问过这个问题,但建议的解决方案都不适合我。我有以下内容:

  var regex = new RegExp(/D0030001 IN/gi);
$("p").filter(function () {
return regex.test(this.id);
}).css("background-color","blue");

这个效果很好。但是,当我尝试这样做时

 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");

这个不行。换句话说,我需要使用变量来构造正则表达式模式。谢谢

最佳答案

您需要使用 RegExp 构造函数的第二个参数来设置标志,并且不需要 // 分隔符。

var regex = new RegExp(spl[0] + " " + spl[1], "gi");

关于javascript - 正则表达式 Javascript 在模式中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27246754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com