Axel Rauschmayer (2013-08-24T20:45:29.000Z)
An example to make things clearer (thanks for the suggestion, Domenic):

https://gist.github.com/rauschma/6330265


On Aug 24, 2013, at 21:43 , Axel Rauschmayer <axel at rauschma.de> wrote:

> Well, obviously it doesn’t make much sense to do that for `text()`, but it would be great to have for `exec()`.
> 
> On Aug 24, 2013, at 21:39 , Axel Rauschmayer <axel at rauschma.de> wrote:
> 
>> At the moment, the following two methods abuse regular expressions as iterators (if the /g flag is set):
>> 
>> * `RegExp.prototype.test()`
>> * `RegExp.prototype.exec()`
>> 
>> Would it make sense to create similar methods that return something iterable, so that for-of can iterate over the result?

-- 
Dr. Axel Rauschmayer
axel at rauschma.de

home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130824/53aec06f/attachment.html>
forbes at lindesay.co.uk (2013-08-25T00:55:48.771Z)
An example to make things clearer (thanks for the suggestion, Domenic):

```javascript
console.log(extractTagNamesES5('<a> and <b> or <c>'));  // [ 'a', 'b', 'c' ]
 
// If exec() is invoked on a regular expression whose flag /g is set
// then the regular expression is abused as an iterator:
// Its property `lastIndex` tracks how far along the iteration is
// and must be reset. It also means that the regular expression can’t be frozen.
var regexES5 = /<(.*?)>/g;
function extractTagNamesES5(str) {
    regexES5.lastIndex = 0;  // to be safe
    var results = [];
    while (true) {
        var match = regexES5.exec(str);
        if (!match) break;
        results.push(match[1]);
    }
    return results;
}
 
// If we had a method `execMultiple()` that returns an iterable,
// the above code would become simpler in ES6.
const REGEX_ES6 = /<(.*?)>/;  // no need to set flag /g
function extractTagNamesES6a(str) {
    let results = [];
    for (let match of REGEX_ES6.execMultiple(str)) {
         results.push(match[1]);
    }
    return results;
}
 
// Even shorter:
function extractTagNamesES6b(str) {
    return Array.from(REGEX_ES6.execMultiple(str), x => x[1]);
}
 
// Shorter yet:
function extractTagNamesES6c(str) {
    return [ for (x of REGEX_ES6.execMultiple(str)) x[1] ];
}
```

https://gist.github.com/rauschma/6330265