JavaScript matchAll() method
The matchAll()
method in JavaScript is used to search a string for all matches against a regular expression (regexp) and returns an iterator of all matched results. This method is particularly useful for obtaining all matches from a string, including capturing groups, in a more straightforward way than using the match()
method with the global (g
) flag.
Syntax:
regexp
: A regular expression object that specifies the pattern to search for. It must have the global (g
) flag to find all matches.
Return Value:
- Returns an iterator (of type
Iterator<RegExpMatchArray>
) containingRegExpMatchArray
objects for each match found in the string. - Each
RegExpMatchArray
contains the full match as well as any capturing groups.
Example 1: Basic Usage
Here's a simple example of using matchAll()
to find all occurrences of a substring.
Output:
Example 2: Capturing Groups
If you include capturing groups in the regular expression, matchAll()
will return each match along with the values of those groups.
Output:
Example 3: Using Array.from()
You can convert the iterator returned by matchAll()
into an array using Array.from()
or the spread operator.
Output:
Example 4: Performance Considerations
Using matchAll()
is generally more efficient than calling match()
in a loop when dealing with global matches, especially for large strings, as it retrieves all matches in a single pass.
Example 5: When Not to Use
If you do not need capturing groups or are only interested in the first match, it may be simpler to use the match()
method.
Summary:
- The
matchAll()
method is used to find all matches of a regular expression in a string and returns an iterator of all matched results. - It must use a regular expression with the global (
g
) flag to find all matches. - Each match returned includes the full match and any capturing groups, making it more versatile than
match()
. - You can easily convert the iterator to an array using
Array.from()
or the spread operator. - It’s particularly useful for working with multiple matches and capturing groups without needing to manage the state of the search manually.