ECMAScript proposal: String.prototype.replaceAll

The normal string method .replace() only lets you replace one occurrence if you search for string (and not a regular expression with the flag /g). The proposal “String.prototype.replaceAll” (by Peter Marshall, Jakob Gruber, Mathias Bynens) fixes that.

.replaceAll() throws an exception if we use a regular expression that does not have the flag /g. The assumption is that we made a mistake and should switch to .replace() if we really only want to replace the first occurrence. The following code demonstrates that:

assert.throws(
() =>'abcdef'.replaceAll(/abc/, 'x'),
TypeError
);

Other than that, .replaceAll() works like .replace(). This table summarizes the differences between .replace() and .replaceAll():