String.prototype.matchAll returns an iterator of matches from a global regular expression. Unlike match with a global regex, it preserves each match’s capture groups; it also produces matches lazily as you iterate. section 12.3 section 12.4.2
Keep these rules in mind:
- Pass a global regex; calling matchAll with a non-global regex throws an error. section 12.3
- Iterate over the results with for…of to process matches one at a time. Each result includes the full match and any captures. section 12.4.2
- Use match when you want all full matches immediately; use matchAll when you need captures from a global regex or lazy iteration. section 12.4.2
Listing 12.6 Finding multiple matches with a global regex
const ninjaRoster =
"Hattori of Iga, Yoshi of Koga, Fuma of Hojo";
const titleRegex = /([^\s,]+) of ([^\s,]+)/g; #A
for (const found of ninjaRoster.matchAll( #B
titleRegex, #B
)) { #B
const [, name, clan] = found; #C
console.log(
`${name} hails from the ${clan} clan`,
);
}
The global regex captures a name and clan for each roster entry; the loop reads those captures from each match result. section 12.4.2
