JavaScript replaceAll

网上的:

复制代码
String.prototype.replaceAll = function(str1, str2) {
    var str = this;
    var result = str.replace(eval("/" + str1 + "/gi"), str2);
    return result;
}

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

String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}
复制代码

这几种其实在特殊字符时无效

  String.prototype.replaceAll = function (oldStr, newStr) {
            var content = this;
            while (content.indexOf(oldStr) >= 0) {
                content = content.replace(oldStr, newStr);
            }
            return content;
        }
   var val = "[red][b]&lt;script&gt;alert('asdfsd');&lt;/script&gt;[/b][/red]<br>";
        val = val.replaceAll('[b]', '<b>'); 
        val = val.replaceAll('[/b]', '</b>'); 
        val = val.replaceAll("[red]", "<font color='red'>"); 
        val = val.replaceAll("[/red]", "</font>");

        alert(val);

 

 

posted @   hongdada  阅读(666)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示