jquery - 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 + ']';
});
声明为变量时的正则表达式不起作用
解决方案
第一个代码不起作用,因为它是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 + ']'}));
第二个代码有效,因为它是正则表达式
推荐阅读
- ios - 'CC_MD5' is deprecated: first deprecated in iOS 13.0 - This function is cryptographically broken and should.。
- javascript - 在 npm install 之后我收到错误:Prototype Pollution in set-value
- android - 为什么 Chrome 自定义标签区域设置不一致?
- javascript - Frida 服务器应用程序在与 Android 设备挂钩时崩溃
- r - 为什么 ggsave() 输出的字体与我指定的字体不同并显示在 RStudio 查看器中?
- ios - 完成检索数据后,如何从 Alamofire 请求中返回 DataModel?
- java - 如何解析来自 URL 的 JSONS 数组的对象?
- xamarin - 构建 Xamarin Android 绑定库时出现 NullReferenceException
- python - Python逆步切片
- java - 任务 main() 执行失败