
ECMAScript proposal: String.prototype.replaceAll - joeyespo
https://2ality.com/2019/12/string-prototype-replaceall.html
======
bendiksolheim
I don’t understand the rationale behind throwing an exception if you provide a
regular expression which lacks the g modifier. This seems really counter
intuitive. I would expect replaceAll to replace all occurrences no matter if
the regular expression is global or not.

~~~
tmpfile
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...](https://github.com/es-
shims/String.prototype.replaceAll/blob/master/implementation.js)

~~~
vimslayer
Your implementation is missing features like capture-based substitions

    
    
         // Remove repeated characters
         'foobar'.replace(/(.)\1+/g, '$1')
         "fobar"
    

and overriding behaviour with Symbol.replace

~~~
tmpfile
You'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 || "");
        }

------
zzo38computer
I would have make the "escapeForRegExp" function built-in (it seems to me the
kind of thing should be built-in), perhaps called RegExp.quote. (I would also
to add support for many features of PCRE.)

~~~
phpnode
There's a proposal for RegExp.escape() which was rejected by TC39 for imho
quite silly reasons:
[https://github.com/benjamingr/RegExp.escape/issues/37](https://github.com/benjamingr/RegExp.escape/issues/37)

~~~
pjtr
I don't understand the reasons. What is the actual problem in this "even-odd
problem"?

How do all the other languages that have an equivalent function (Perl
quotemeta, PHP preg_quote, Python re.escape, Ruby: Regexp.escape, Java
Pattern.quote, C# Regex.Escape, Go QuoteMeta, Rust regex::escape) avoid or
deal with this problem?

~~~
scrollaway
They don't. The reasons are frankly idiotic.

The first couple of comments as well as the very last one from April in that
thread all sum it up quite well.

------
rienbdj
I wish the pipeline operator were standardised so we can stop fiddling with
prototypes.

------
robbrown451
This would be nice, using RegEx's for such simple cases is ugly, especially if
the replace string is dynamic (so can't be done with a literal).

I find myself using a combination of split and join a lot to avoid that.

~~~
deith
And because regexes are regexes, so one might introduce bugs by not escaping
what's meant to be escaped. (I didn't read the article so maybe he mentions
this already)

------
kapv89
I think JS has had enough of syntactic sugar like features. What it needs as a
next step in its natural evolution is support for proper multi-threading with
atomics, mutex etc.

~~~
bobbytherobot
What would you do with multi-threading in JS? I/O is already non-blocking
which is a big reason for using multi-threading.

------
biolurker1
So much fuss for a small function

~~~
happytoexplain
It being small does not mean it's not critically important to get the details
right. In fact, if there's any correlation between smallness and frequency of
use, then it's actually _more_ important to go to the full lengths of fuss
resolution.

~~~
biolurker1
Really you think in 2020 the software world should have an open discussion
about a string replace function? Ok

~~~
the_other
For the world’s most popular language? Yes.

------
yepthatsreality
Mmmmm...syntactic sugar...

~~~
DDR0
Could you provide an example of what this desugars to? I'm not sure I
understand.

~~~
pier25
You can simply use string.replace() with a global regex.

~~~
minitech
Dynamic patterns require escaping, resulting in unnecessary complexity and
overhead.

------
pier25
While this is a nice little addition to the language, personally I'd prefer to
see more substantial changes like decorators, observables, class properties,
optional static types, etc.

~~~
mccraveiro
Class properties are already part of the language

~~~
pier25
My bad, I meant class fields which are stage 3:

[https://github.com/tc39/proposal-class-
fields](https://github.com/tc39/proposal-class-fields)

[https://tc39.es/proposal-class-fields/](https://tc39.es/proposal-class-
fields/)

------
2ion
Exhibit $n why ECMAScript is not a well-designed language at its core. It
ought to be as simple as the Lua core language but it isn't (the object type
was a good start but then stopped being one). Boltons after boltons. For
things as simple as this.

~~~
snek
lua has s:gsub, which is basically the same thing... or are you saying js
should've popped into existence with thousands of stdlib functions?

~~~
mschuster91
PHP at least is sane enough to provide the C stdlib, dito for Java.

JavaScript... well, remember left-pad? That's what happens when people are
forced to re invent the wheels.

~~~
krapp
left-pad wasn't a fault of the language, but the modern javascript ecosystem
and its tools. Javascript development got along fine for years when all anyone
had was JQuery plugins, no one was complaining about the lack of a C style
stdlib, and no single point of failure for the entire ecosystem created an
internet-wide catastrophe every week.

~~~
ben-schaaf
Everyone complained about the lack of a C style stdlib. _That 's why jQuery
was written and everyone used it_.

~~~
krapp
People complained about incompatible versions of the DOM between IE and
everyone else, and about how awkward AJAX and DOM manipulation was, and those
are the problems JQuery solved. That's providing a common API and mostly
forcing Microsoft to follow spec, not a "C style stdlib," though.

I don't think many people were upset that javascript didn't natively support,
say, proper integers or static types or (ugh) "classes" or what have you, at
least not until people started wanting to use javascript outside of its
intended purpose.

------
tomaszs
Couldnt we just have an object called String2 with a replace method that
replaces all occurances without any regex at all? Like in any other language?
We could fix entire Javascript just by adding two to all object names.

~~~
soylentgraham
This is such a terrible idea.

~~~
tomaszs
You right. We should have Javascript2 language.

~~~
herohamp
[https://xkcd.com/927/](https://xkcd.com/927/)

~~~
tomaszs
This strip is about creating unifications based on two things that are not
standarized. While the idea is to make a new JS branch that will solve issues
gathered through years. So the strip does not apply here. Also, while it has
some point with extreme unification efforts, there is a vast range of
unification projects that actually delivered what they promised to.

