~80b ponyfill for String.prototype.replaceAll() with good performance.
Why ponyfill? Because this is a proposal for a spec, and polyfilling it in-place before it gets solidified could break code that relies on an incorrect implementation.
Alternate Version
This version trades a bit of size and performance for reduced memory usage.
const replaceAll = ''.replaceAll
? (str, find, rep) => str.replaceAll(find, rep)
: (str, find, rep) => {
let s = '', index, next;
while (~(next = str.indexOf(find, index))) {
s += str.substring(index, next) + rep;
index = next + find.length;
}
return s + str.substring(index);
}
See Polyfill Version
Don't use this, for the reason explained above.
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(find, replace) {
return this.split(find).join(replace);
};
}
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(find, replace) {
let s = '', index, next;
while (~(next = this.indexOf(find, index))) {
s += this.substring(index, next) + replace;
index = next + find.length;
}
return s + this.substring(index);
};
}
This implementation is not fully standards compliant. MDN says here that the replacement can be a function which takes the RegExp match as input.