jQuery-正则表达式与名称替换一起使用时不起作用-在变量中传递时

时间:2019-01-29 23:18:15

标签: jquery regex

请看看您能否在下面解释此代码

//The code below does not work
var regEx = "/myList\\[[0-9]\\]/gi";
this.name =this.name.replace(regEx , function (x) {
  return 'myList[' + index + ']';
});

//The code below Works
this.name = this.name.replace(/myList\[[0-9]\]/gi, function (x) {
  return 'myList[' + index + ']';
});    

正则表达式声明为变量时不起作用

1 个答案:

答案 0 :(得分:0)

第一个代码不起作用,因为它是String而不是regex,因此需要使用RegExp对象才能工作

//Had to use RegExp to make it work 
var name = "x.y.myList[0].test";
var regEx2 = new RegExp("myList\\[[0-9]\\]", "gi");
alert(name.replace(regEx2 , function (x) { return 'myList[' + 1 + ']'}));

第二个代码有效,因为它是正则表达式