The syntax of the matchAll()
method is:
str.matchAll(regexp)
Here, str
is a string.
matchAll() Parameters
The matchAll()
method takes in:
- regexp - A regular expression object (Argument is implicitly converted to
RegExp
if it is a non-RegExp
object)
Note: If RegExp
object does not have the /g
flag, a TypeError
will be thrown.
Return value from matchAll()
- Returns an iterator containing the matches including the capturing groups.
Note: The returned iterator's each item will have the following additional properties:
groups
- An object of named capturing groups having keys as the names and values as the captured matches.index
- The index of search where the result was found.input
- A copy of the search string.
Example 1: Using matchAll()
const string = "I am learning JavaScript not Java.";
const re = /Java[a-z]*/gi;
let result = string.matchAll(re);
for (match of result) {
console.log(match);
}
Output
[ 'JavaScript', index: 14, input: 'I am learning JavaScript not Java.', groups: undefined ] [ 'Java', index: 29, input: 'I am learning JavaScript not Java.', groups: undefined ]
Here, the returned iterator is iterated over using the for...of
loop.
Example 2: Using matchAll to capture groups
const string = "My name is Albert. YOUR NAME is Soyuj.";
// expression matches case-insensitive "name is"+ any alphabets till period (.)
// using named capturing groups
const re = /name\sis\s(?<name>[a-zA-Z]+)\./gi;
let found = string.matchAll(re);
for (const match of found){
console.log(`Found "${match[0]}" at index ${match.index}. Captured name = ${match.groups['name']}`)
}
Output
Found "name is Albert." at index 3. Captured name = Albert Found "NAME is Soyuj." at index 24. Captured name = Soyuj
Here, we have used a regular expression to match a certain portion of the string. We can capture certain groups in the match using matchAll()
better than match()
.
Recommended Reading: JavaScript String match()