The matchAll() method of the String class in JavaScript returns an iterator of all the matches of a regular expression against a string. It provides a more comprehensive way to retrieve multiple matches along with capturing groups.
The syntax of String.matchAll() method is:
matchAll(regexp)
This matchAll() method of String returns an iterator of all regexp's matches.
Parameter | Optional/Required | Description |
---|---|---|
regexp | required | A regular expression object. If a non-RegExp object is passed, it is implicitly converted to a RegExp. |
String.matchAll() returns value of type Iterator
.
In this example, we use the matchAll()
method to find all occurrences of the letter 'o' in a string.
For example,
str
with the value 'Hello World'
.matchAll()
method on str
with the regular expression /o/g
to find all matches of the letter 'o'.Array.from()
method and stored in the variable matches
.matches
to the console using console.log()
method.const str = 'Hello World';
const matches = Array.from(str.matchAll(/o/g));
console.log(matches);
[['o'], ['o']]
This example demonstrates using the matchAll()
method to find all occurrences of a pattern with capturing groups.
For example,
str
with the value '2021-01-01 and 2022-12-31'
.matchAll()
method on str
with the regular expression /(\d{4})-(\d{2})-(\d{2})/g
to find all date patterns and their capturing groups.Array.from()
method and stored in the variable matches
.matches
to the console using console.log()
method.const str = '2021-01-01 and 2022-12-31';
const matches = Array.from(str.matchAll(/(\d{4})-(\d{2})-(\d{2})/g));
console.log(matches);
[['2021-01-01', '2021', '01', '01'], ['2022-12-31', '2022', '12', '31']]
In this example, we use the matchAll()
method with a non-global regular expression, which results in a single match.
For example,
str
with the value 'foo bar baz'
.matchAll()
method on str
with the regular expression /ba./
to find the first occurrence of 'ba' followed by any character.Array.from()
method and stored in the variable matches
.matches
to the console using console.log()
method.const str = 'foo bar baz';
const matches = Array.from(str.matchAll(/ba./));
console.log(matches);
[['bar']]
In this JavaScript tutorial, we learned about matchAll() method of String: the syntax and few working examples with output and detailed explanation for each example.