I want to replace all occurences of a pattern in a string by another string. For example, lets convert all \"$\" to \"!\":
\"$$$\" -> \"!!!\"
<
"Plain string.replace replaces only the first match"
In that case, depending on how efficient you need the replace operation to be, you could do:
String.prototype.my_replace_all_simple = function(f, r) {
var newstr = "";
for (var i = 0; i < this.length; ++i) {
if (this[i] == f) {
newstr += r;
} else {
newstr += this[i];
}
}
return newstr;
};
or
String.prototype.my_replace_all = function (f, r) {
if (this.length === 0 || f.length === 0) {
return this;
}
var substart = 0;
var end = this.length;
var newstr = "";
while (true) {
var subend = this.indexOf(f, substart);
if (subend === -1) subend = end;
newstr += this.substring(substart, subend);
if (subend === end) {
break;
}
newstr += r;
substart = subend + f.length;
}
return newstr;
};
// Adapted from C++ code that uses iterators.
// Might have converted it incorrectly though.
for example.
But, I'd just use Mark's suggested way.