网上 copy 的一段 javascript 代码 String.prototype.replaceAll = fucntion(){...} 存在问题

早些年,浏览器没有内置 字符串的 replaceAll()方法,就从网上 copy 了一段 replaceAll() 的实现:

String.prototype.replaceAll=function(AFindText,ARepText){raRegExp=new RegExp(AFindText,"g");return this.replace(raRegExp,ARepText)}

今天突然遇到一个问题,定位到了这段代码,我才发现,这个实现存在问题:

var str = "aaa\\\\bbb"; //当代码中含有两个连续的 '\'

console.log(str.replaceAll("\\", "\\\\"));

控制台直接抛出错误:

VM25:1 Uncaught SyntaxError: Invalid regular expression: /\/: \ at end of pattern
 at new RegExp (<anonymous>) at String.replaceAll (<anonymous>:1:67)
 at <anonymous>:1:17

后来找到一篇相关的介绍:

Node.js和javascript中RegExp对象的风险及防范

https://www.jianshu.com/p/67aeaf115a2d

才搞明白缘由。

正确的实现:

if(String.prototype.replaceAll == null){
String.prototype.replaceAll=function(AFindText,ARepText){AFindText=AFindText.replace(/\\/ig, "\\\\");raRegExp=new RegExp(AFindText,"g");return this.replace(raRegExp,ARepText)}}

主要增加了这么一句:

AFindText=AFindText.replace(/\\/ig, "\\\\");

 

网上关于 String.prototype.replaceAll=function(...){...} 的实现基本上都存在这个问题。

 

posted @ 2024-06-10 10:01  personnel  阅读(2)  评论(0编辑  收藏  举报
友情链接:图片批量处理工具 gif动态图制作工具 制作电子相册 图片排版工具 制作淘宝主图视频 MKScript 鼠标键盘自动化脚本语言