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 Methods
Regular Expression Search and Replace can be done with different methods.
These are the most common:
String Methods
Method | Description |
---|---|
match() | Returns an Array of results |
matchAll() | Returns an Iterator of results |
replace() | Returns a new String |
replaceAll() | Returns a new String |
search() | Returns the index of the first match |
split() | Returns an Array of results |
RegExp Methods
Method | Description |
---|---|
exec() | Returns an Iterator of results |
test() | Returns 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 |