当前位置:Gxlcms > JavaScript > JavaScript实现的字符串replaceAll函数代码分享

JavaScript实现的字符串replaceAll函数代码分享

时间:2021-07-01 10:21:17 帮助过:3人阅读

由于javascript中的replace函数无法替换全部匹配的字符串,所以需要为String类增加一个方法,代码如下:

代码如下:
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);  
     } else {  
        return this.replace(reallyDo, replaceWith);  
     }  
}

人气教程排行