Menu Home

String.matchAll()

Hi everyone, and welcome to another thrill-ride adventure in Boring JavaScript! Today, we cover the String.matchAll() method.

Don’t like to read? See the video.

Swiping Left

Back in the olden days – you know, last year – to find all matches in a string you used something like the RegExp.exec() method to loop through a string and get all the results. Like this:

const animals = "Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale";

const catRegExp = /,?([A-Za-z]*?[Cc]at),?/g;

let myCats = catRegExp.exec(animals);

while (myCats !== null) {
	console.log(myCats);
	myCats = catRegExp.exec(animals);
}

/* output (truncated here for space considerations)

[
  'Cat,', 'Cat', index: 0,
]
[
  ',Wildcat,', 'Wildcat', index: 57,
]
[
  ',Bobcat,', 'Bobcat', index: 79,
]
*/

This was all well and good, but presented a problem. You had to run the ‘exec()’ method within the loop on the same string in order to get to each entry in your string. This means that ‘exec()’ gave two different answers to the same operation (Lines 6 and 10). This is not a good programming practice.

So the JavaScript Grand Council in Rivendell decided to make things easier on us by introducing a way to retrieve all the matches at one time. And the result is the String.matchAll() method.

Matchmaker, Matchmaker, Make Me a Match

The syntax of the String.matchAll() is very simple. It takes one argument, a Regular Expression that is used as a pattern to match against the string. It will return the exact same data as did the exec() method above. The big difference is that String.matchAll() returns all the matches using an iterator. This means one call does it all, and you can use all your fun iterator methods to get the information.

Here is an example:

const animals = "Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale";

const myCats = animals.matchAll(/,?([A-Za-z]*?[Cc]at),?/g);

for (const cat of myCats) {
	console.log(cat);
}

/* output (Full output shown this time)
[
  'Cat,',
  'Cat',
  index: 0,
  input: 'Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale',
  groups: undefined
]
[
  ',Wildcat,',
  'Wildcat',
  index: 57,
  input: 'Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale',
  groups: undefined
]
[
  ',Bobcat,',
  'Bobcat',
  index: 79,
  input: 'Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale',
  groups: undefined
]
*/

As you can tell by the code, because we didn’t have to call String.matchAll() again like we did with exec(), our code is simpler to understand.

The Output

String.matchAll() returns each entry as an array, exactly as did RegExp.exec(). Let’s look at the contents of that array:

Array EntryExampleDescription
entry[0],Bobcat,The match on the original string
entry[1]BobcatThe match when the grouping is applied.
entry.index79The character position in the original string of the match
entry.inputCat,Dog,…The original string
entry.groupsundefinedAny named groupings (see below)

If you use groupings (as we did in our regex), then ‘entry[1]’ will give us the final value we need for whatever our code needs.

And What About that ‘Groups’?

So what is that ‘groups’ property in our entry? That is if you used Named Groups in your regular expression. Let’s see how that works:

const animals = "Cat,Dog,Horse,Cow,Coyote,Road Runner,Dolphin,Whale,Lizard,Wildcat,Dog,Horse,Cow,Bobcat,Whale";

const myCats = animals.matchAll(/,?(?<name>[A-Za-z]*?[Cc]at),?/g);

for (const cat of myCats) {
	console.log(cat.groups.name);
}

/* output

Cat
Wildcat
Bobcat

*/

Notice the change in Line 4. Our regular expression now includes what is called a ‘Named Group’, which we have given the name … well … ‘name’. We can then access this named group as a property of the ‘groups’ property for each entry in our returned iterator (Line 7). This makes access to the data we need easier and better understood for those who might read our code later.

The Video

As always, we created a video on today’s post.

Shameless Plug

Catch us everywhere!

TheVirtuoid – Our main site

Facebook

Youtube

Twitter

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: