What is string.matchall() in JavaScript?

The matchAll() function matches a string against a regular expression and returns an iterator of all the matched groups.

Syntax

str.matchAll(regexp)

RegExp

  • The RegExp argument must have the /g flag. Otherwise, a TypeError will be thrown.
  • If we pass a non-RegExp object, then the values are internally converted to a RegExp object using new Regexp(value).

Return value

matchAll() returns an iterator that has an array for each match. In that array, we have:

  • groups - An object of the named capturing groups, which has the name of the captured group as the key and the match as the value.
  • index - The index at which the match for the RegExp is found.
  • input - The search string.

Example

const regex = /J(ava)([a-z]*)/gi;
let str = "Java JavaScript";
let allMatchItr = str.matchAll(regex);
for(match of allMatchItr) {
console.log("\n-----match-----\n");
console.log(match);
}

In the code above, we have two matches for the RegExp /J(ava)([a-z]*)/gi; so, the matchAll() method returns an iterator with two array values. In each array:

  • The first element is the matched text.
  • For each matched item on a parenthetical capture group, there will be one element.
  • The array, which contains the index, input, and groups.

Example of captured group names

const regex = /J(?<group_name_1>ava)(?<group_name_2>[a-z]*)/gi;
let str = "Java JavaScript";
let allMatchItr = str.matchAll(regex);
for(match of allMatchItr) {
console.log("\n-------Match-------\n");
console.log("Matched String =>", match[0]);
console.log("Matched value of group_name_1 => ", match.groups['group_name_1']);
console.log("Matched value of group_name_2 => ", match.groups['group_name_2']);
}

In the above code, we printed the matched string, which is present at the 0th index of the array. We named the captured group as group_name_1 and group_name_2 in the regex. Each array present in the returned iterator contains the group’s property with the group names as the keys and the matched strings as the values.

Free Resources