Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.matchAll

Returns every match together with its groups.

Available since: ES2020

Syntax

str.matchAll(regexp)

Parameters

ParameterTypeDescription
regexpRegExpA regular expression; it must have the g flag.

Return value

IteratorAn iterator of matches, each with groups and a position.

Examples

All key=value pairs:

const text = 'a=1, b=2, c=3';
 
for (const match of text.matchAll(/(\w)=(\d)/g)) {
  console.log(match[1], match[2], match.index);
}

Output:

a 1 0
b 2 5
c 3 10

Matches into an object via named groups:

const text = 'width=300 height=200';
const entries = [...text.matchAll(/(?<key>\w+)=(?<value>\d+)/g)].map((m) => [m.groups.key, Number(m.groups.value)]);
 
console.log(Object.fromEntries(entries));

Output:

{
  "width": 300,
  "height": 200
}

Notes

Without the g flag the method throws a TypeError. Unlike match() with g, it keeps the groups of every match.

See also

In the tutorial

  • Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.

Thanks for reading!

Donate to the site — we work hard for you.