首页 > 语言 > JavaScript > 正文

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

2024-05-06 14:43:51
字体:
来源:转载
供稿:网友

由于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);  
     }  
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选