JS Built-ins
StringString.prototype.matchAllintermediate

String.prototype.matchAll() β€” collect all matches

πŸ“– Usage Example
const str = 'a1 b2 c3'
const matches = [...str.matchAll(/(w)(d)/g)]
matches.length   // β†’ 3
matches[0][1]    // β†’ 'a'

Use matchAll() with the g flag to iterate over all regex matches and access capture groups in each result.

String.prototype.matchAll()

str.matchAll(regexp) returns an iterator of all regex match results. The regex must use the g flag.

Use spread [...str.matchAll(re)] to get an array.

Challenge: Implement countMatches(str, re) that returns the number of matches.

countMatches('aababc', /a/g) // β†’ 3
πŸ’‘ Hints (2)
  • β€’ Spread the iterator into an array: `[...str.matchAll(re)]`.
  • β€’ The `g` flag is required for `matchAll`.