Letting RegExp method return something iterable?

Andrea Giammarchi andrea.giammarchi at gmail.com
Thu Aug 29 09:36:56 PDT 2013


then you are probably looking for something like this?

```javascript
String.prototype.matchAll = function (re) {
  for (var
    re = new RegExp(
      re.source,
      "g" +
      (re.ignoreCase ? "i" : "") +
      (re.multiline ? "m" : "")
    ),
    a = [],
    m; m = re.exec(this);
    a.push(m)
  );
  return a;
};

// example
'abcdefgh'.matchAll(/.(.)/g);

[
  ["ab", "b"],
  ["cd", "d"],
  ["ef", "f"],
  ["gh", "h"]
]
```


On Thu, Aug 29, 2013 at 9:24 AM, Oliver Hunt <oliver at apple.com> wrote:

>
> On Aug 29, 2013, at 1:13 AM, Brendan Eich <brendan at mozilla.com> wrote:
>
> > Axel Rauschmayer wrote:
> >> * /g flag must be set
> >> * lastIndex must be 0
> >> * can’t inline the regex, because it is needed as a pseudo-iterator
> (more of an anti-pattern, anyway, but still)
> >> * side effects via lastIndex may be a problem
> >
> > Anything we do of the execAll/execIter kind had better be immune to the
> awful Perl4-infused "mutable lastIndex state but only if global" kind.
> Compositionality required.
> >
> > The design decision to face is what to do when a global regexp is used.
> Throw, or ignore its lastIndex?
>
> I would favor ignoring lastIndex rather than throwing, but to be sure can
> you clarify what you mean by global regexp?
>
> If we're talking /.../g, then my feeling is that the /g should be ignored
> -- if you're wanting a regexp iterator for a string (or whatever) I would
> think that the API would imply that all regexps were intended to be
> "global".
>
> If we're talking about multiple concurrent iterators with the same
> regexp/string then it should definitely be ignored :D
>
> Erm.
>
> I'm not sure if that's coherent, but the TLDR is that I favor ignoring all
> the old side state warts (i would not have iterators update the magic $
> properties, etc)
>
> --Oliver
>
> >
> > /be
> > _______________________________________________
> > es-discuss mailing list
> > es-discuss at mozilla.org
> > https://mail.mozilla.org/listinfo/es-discuss
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130829/6df42763/attachment-0001.html>


More information about the es-discuss mailing list