When using a Regular Expression to pull matches from a string with matchAll(), the resulting Iterable Object that is spread into an Array object with the spread operator shows nested arrays with multiple members.
const regexUpperCaseTo = /(?<=\x2d|\x5f)[a-zA-Z0-9]/g;
const testVar1 = [...str.matchAll(regexUpperCaseTo)]
when we print out testVar1 it shows:
[
[ 's', index: 4, input: 'the-stealth-warrior', groups: undefined ],
[ 'w', index: 12, input: 'the-stealth-warrior', groups: undefined ]
]
Similarly, being an iterable object, we can use a for/of loop to iterate over each element of the returned array.
[ 's', index: 4, input: 'the-stealth-warrior', groups: undefined ]
[ 'w', index: 12, input: 'the-stealth-warrior', groups: undefined ]
However, once we test each member for length, it returns 1.
console.log(testVar1.forEach(x => console.log(x.length)))
and in addition to this, when we try to access the members of each array beyond the 0th member it returns undefined.
What is going on here that each member returned only seems to consist of the first element?
This is normal (and has nothing to do with the iterator that matchAll
returns). Each match - just like those returned from .match()
and .exec()
- is an array object with the whole match and the captured groups as elements.
Additionally, the array has some special properties like .index
, .input
and (since ES2018) .groups
. See also Return positions of a regex match() in Javascript? or Contents of a RegExp match.