ssube
ssube

Reputation: 48287

Will ES6 RegExps support the Iterator protocol?

I'm unable to find an answer in the spec or list of proposals as to whether RegExps in ES6 will provide the necessary methods to support the Iterator protocol for matched groups. There are a number of symbol methods, but I'm not familiar enough with the semantics of the various symbols to tell if they will provide this.

I would imagine something like:

var rex = /((\w+)\s?)*/;
var res = rex.exec("test string");

console.log(res);

for (let match of res) {
    console.log(match);
}

This seems to work in 6to5's REPL, logging the expected "test string", "string", "string".

Is this specifically defined in the ES6 spec, and if not, what properties of the regex result allow it to work? Or is it just an artifact of 6to5 not being exactly ES6?

Upvotes: 2

Views: 144

Answers (1)

alexpods
alexpods

Reputation: 48525

res is just an Array of matches. You can check it using one of the next variants:

Object.prototype.toString.call(res) === '[object Array]'
res instanceof Array;
Array.isArray(res);
res.constructor === Array;

And arrays in ES6 supports iterator interface. See here, or in MDN: Array.prototype[@@iterator]

What about input and index properties - they just added to the res array by exec method. For example you can check v8 source code:

Upvotes: 3

Related Questions