[1]: https://github.com/tc39/proposal-string-replaceall/issues/16
Chrome: deprecating and removing Custom Elements V0 in 2020.
Browser implementors though... They take a much more callous approach.
How many more websites are using it because it was out, and implemented?
/* Usage:
> 'abcdefabc'.replaceAll('abc')
'def'
> 'abcdefabc'.replaceAll('abc', '+')
'+def+'
> 'abcdefabc'.replaceAll(/abc/, '+')
'+def+'
> 'abcdefabc'.replaceAll(/abc/g, '+')
'+def+'
*/
String.prototype.replaceAll = function (re_or_str, sub) {
return this.split(re_or_str).join(sub||'')
}
On a side note, is it just me or does the linked polyfill for String.prototype.replaceAll [1] seem wildly complex???[1] https://github.com/es-shims/String.prototype.replaceAll/blob...
// Remove repeated characters
'foobar'.replace(/(.)\1+/g, '$1')
"fobar"
and overriding behaviour with Symbol.replace String.prototype.replaceAll = function (n, sub) {
let t, f = "g";
if (n instanceof RegExp) {
t = n.source;
f = n.flags;
if (!f.includes("g"))
f += "g";
} else {
t = RegExp.escape(n);
}
let r = new RegExp(t, f);
return this.replace(r, sub || "");
}Unlike the string case, the regexp case has a way of communicating that you want to match every instance versus only the first
However, if you just want to replace plain strings, `.replaceAll()` actually gives you a fundamentally better API: you can now use `str.replace(s,r)` for single replace, and the intuitive companion function `str.replaceAll(s,r)` for all-instances replace. No "learning/knowing regexp" required just to replace some plain text.
I agree that only replacing the first occurrence is the wrong solution. That would be surprising. The only correct solution to this is in my opinion auto-g-ing the regular expression, no matter how unusual that is. There is no way you would write replaceAll() as a mistake when you actually just meant replace().
<<There is no way you would write replaceAll() as a mistake when you actually just meant replace(). >>
Have you ever reviewed the daily work of colleagues or contributors who haven't used JS day in day for the last 2 years? That's exactly the kind of mistake that happens _all_ the time. And people new to JS are more than happy to reach for regex well before there's a good reason to use them.
Just tried `string.match` and `regex.exec` and could only get the first match.
let flagified = new RegExp(original.source, original.flags + "g")
or modify the regex standards as part of the proposal.