JavaScript String matchAll()
Before ES2020 there was no string method that could be used to search for all occurrences of a string in a string.
If the parameter is a regular expression, the global flag (g) must be set set, otherwise a TypeError is thrown.
If you want to search case insensitive, the insensitive flag (i) must be set:
Description
The matchAll()
method matches a string against a regular expression **
The matchAll()
method returns an array with the matches.
The matchAll()
method returns null if no match is found.
Note
** If the search value is a string, it is converted to a regular expression.
See Also:
Syntax
string.matchAll(match)
Parameters
Parameter | Description |
match | Required. The search value. A regular expression (or a string that will be converted to a regular expression). |
Return Values
Type | Description |
Iterator or null | An Iterator containing the matches.null if no match is found. |
The Difference Between
String match() and String search()
The match()
method returns an array of matches.
The search()
method returns the position of the first match.
Regular Expression Search Methods
In JavaScript, a regular expression text search, can be done with different methods.
With a pattern as a regular expression, these are the most common methods:
String Methods
match(pattern) | An Array of results |
matchAll(pattern) | An Iterator of results |
replace(pattern, rep) | A new String |
search(pattern) | Index of the first match |
split(pattern) | An Array of results |
RegExp Methods
pattern.exec() | An Iterator of results |
pattern.test() | true or false |
Browser Support
string.matchAll()
is a JavaScript 2020 feature.
ES 2020 is supported in all modern browsers since September 2020:
Chrome 85 | Edge 85 | Firefox 79 | Safari 14 | Opera 71 |
Aug 2020 | Aug 2020 | Mar 2020 | Sep 2020 | Sep 2020 |