liveBook · Manning

String.prototype.matchAll

As explained in Secrets of the JavaScript Ninja, Third Edition

String.prototype.matchAll is a JavaScript String method that returns an iterator over all matches of a regular expression in a string.

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

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains the global-flag requirement, captured results, lazy iteration, and contrast with match.
Examples
Demonstrates extracting names and clans from a comma-separated ninja roster.
What you can do after
Apply matchAll with a global regex and iterate over matches and their captures.
How it connects
Connects regular expressions, capture groups, and String.prototype.match.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.