首页 > 解决方案 > Jquery - 与名称替换一起使用时,正则表达式不起作用 - 在变量中传递时

问题描述

请看您是否可以在下面解释此代码

//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 + ']';
});    

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

标签: jqueryregex

解决方案


第一个代码不起作用,因为它是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 + ']'}));

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


推荐阅读