ReplaceAll string function

Extends String class with a replaceAll function for strings.

by Preston Badeer

HTML

From <a href="http://dumpsite.com/forum/index.php?topic=4.msg8#msg8">http://dumpsite.com/forum/index.php?topic=4.msg8#msg8</a>

JavaScript

String.prototype.replaceAll = function (str1, str2, ignore) {
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
}

"x".replaceAll("x", "xyz");
// xyz

"x".replaceAll("", "xyz");
// xyzxxyz

"aA".replaceAll("a", "b", true);
// bb

"Hello???".replaceAll("?", "!");
// Hello!!!