‼️ The difference between String.match() and String.matchAll()May 26, 2021JavaScript 298 words

String.match()

String.match() is a method in JavaScript that returns an array of results matching a string against a regular expression.

const regex = /t(e)(st(\d?))/g;
const string = 'test1test2';
const results = string.match(regex);
console.log(results);
// → ['test1', 'test2']

Returned results depends on the global(g) flag. If a g flag is used we will get all results but without capturing groups. If we remove the g flag from the regular expression what we get has all of the capturing groups, but we only get the first match. It looks like this:

const regex = /t(e)(st(\d?))/;
const string = 'test1test2';
const results = string.match(regex);
console.log(results);
// → ['test1', 'e', 'st1', '2', index: 0, input: 'test1test2', groups: undefined]

This string contains a second possible match beginning with 'test2' but we don’t have it. If there are no matches, match() method returns null. Now here’s the question: how do we get all of the capturing groups for each match? That’s where String.matchAll() comes into play.

String.prototype.matchAll()

String.matchAll() returns an iterator that returns all matched groups against a regular expression, including capturing groups. One of the main reasons for using matchAll() over match() is the abilitiy to access capture groups.

const regex = /t(e)(st(\d?))/g;
const string = 'test1test2';
const matches = string.matchAll(regex);
Array.from(matches, console.log);

// -> ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', groups: undefined]
// -> ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', groups: undefined]

Unlike match() which returns an array on a global search, matchAll() returns an iterator that produces an array for every match, which works with for…of loops as well. If there are no matches, matchAll() method returns an empty iterable object.

The iterator produces an array for each match, including the capturing groups with a few extra properties like index, input and groups.

  • index: The index of the first result in the original string. In the above example test2 starts at position 5 hence index has the value 5.
  • input: The complete string that matchAll() was run against. In the above example, that was 'test1test2'.
  • groups: Contains the results of any named capturing groups specified in the regular expression.

⚠️ The regular expression for matchAll() needs to have a g flag, otherwise, an error will be thrown.

TypeError: matchAll must be called with a global RegExp

Conclusion

As we can see the difference between match() and matchAll() is quite significant which means that matchAll() by no means can be looked as a replacement for a match().

If I’ve missed anything please let me know in the comments below.