3 ms·
I agree. I would think replaceAll would behave like the following: /* Usage: > 'abcdefabc'.replaceAll('abc') 'def' > 'abcdefabc'.replaceAll('abc', '+'
by tmpfile 7y ago
I agree. I would think replaceAll would behave like the following:
/*
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/master/implementation.js https://github.com/es-shims/String.prototype.replaceAll/blob...
- jsjohnst 7y agoAgree, seems much more complex than it should need to be, but I’m guessing there’s edge cases (but even then it seems more complex than needed).
- vimslayer 7y agoYour implementation is missing features like capture-based substitions // Remove repeated characters 'foobar'.replace(/(.)\1+/g, '$1') "fobar" and overriding behaviour with Symbol.replace
- deleted 7y ago[deleted]
- tmpfile 7y agoYou're right, my implementation was not a drop-in replacement for replace. How about this? 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 || ""); }