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);
原文地址:https://www.cnblogs.com/hongdada/p/3296145.html