Open In App

Javascript String matchAll() Method

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The matchAll() method is a JavaScript string method used to retrieve all matches of a regular expression within a string.

Syntax:

string.matchAll(regex)
  • string is the string on which the method is called.
  • regex is a regular expression object defining the pattern to search for in the string.

Parameter:

  • Regexp: It is simply a regular expression object. The RegExp object must include the /g flag, else a TypeError is thrown.

Return value:

Returns an iterator containing the matches including the capturing groups.

JavaScript String matchAll() Examples

Example 1: Extracting Multiple Matches with JavaScript matchAll()

The code defines a function myFunction that demonstrates the usage of the matchAll() method. It creates a regular expression /e(xam)(ple(\d?))/g with capturing groups and the global flag. It applies this regex pattern to the string 'example1example2example3' using matchAll(). The resulting array contains match objects, each representing a match and its capturing groups. It prints the first three match objects from the array.

JavaScript
function myFunction() { 
  
    //Regular expression with the /g flag
    const regex = /e(xam)(ple(\d?))/g;
    //Reference string
    const str = 'example1example2example3';
    
    //Using matchAll() method
    const array = [...str.matchAll(regex)];
    
    console.log(array[0]);
    console.log(array[1]);
    console.log(array[2]);
}  
myFunction();

Output

[
'example1',
'xam',
'ple1',
'1',
index: 0,
input: 'example1example2example3',
groups: undefined
]
[
'example2',
'xam',
'ple2',
'2',
index: 8,
input: 'example1example2example3',
groups: undefined
]
[
'example3',
'xam',
'ple3',
'3',
index: 16,
input: 'example1example2example3',
groups: undefined
]

Example 2: Case-Sensitive Match Extraction using matchAll() in JavaScript

This example uses matchAll() with a case-sensitive regex pattern to extract occurrences of “geek” from the input string, iterating over the resulting match objects to log each match.

JavaScript
function extractMatches() {
    const regex = /geek/g; // Case-sensitive regex pattern
    const str = 'Geek, geek, GEEK'; // Input string
    const matches = [...str.matchAll(regex)]; // Extracting matches
    
    for (const match of matches) {
        console.log(match[0]); // Output: 'geek'
    }
}

extractMatches();

Output
geek

We have a complete list of Javascript Strings methods, to check those please go through Javascript String Complete reference article.

Supported Browser:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads