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.matchAll() returns an iterator that returns all matched groups against a regular expression, including capturing groups. One of the main reasons for using
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]
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: The index of the first result in the original string. In the above example
test2starts at position 5 hence
indexhas the value 5.
input: The complete string that
matchAll()was run against. In the above example, that was
groups: Contains the results of any named capturing groups specified in the regular expression.
⚠️ The regular expression for
matchAll()needs to have a
gflag, otherwise, an error will be thrown.
TypeError: matchAll must be called with a global RegExp
As we can see the difference between
matchAll() is quite significant which means that
matchAll() by no means can be looked as a replacement for a
If I’ve missed anything please let me know in the comments below.