matchAll() is a new method of String class provided with ECMAScript 2020 which works with regular expressions. This method returns all matches for a regular expression that exists in a particular string. The matches are returned as an iterator to access them in a one-at-a-time method, or we can use a
for...of loop and convert them to an array and then access it.
The syntax of
string.prototype.matchAll() method is given below:
String - This is the reference string for which matches are to be found.
Regexp - It is a regular expression object which includes /g flag; otherwise, it will through TypeError.
Return Value - The return value will be an iterator containing the matches, including the capturing groups.
Each item of the returned value will have the following properties:
groups - It consists of the result of the named capturing groups specified in the regular expression
index - The index of search where the result was found.
input - A copy of the search string.
Let's understand it better with the help of an example.
In this example, we have demonstrated how we can find the matches using regular expression also captured the internal groups with the help of
<!DOCTYPE html> <html> <head> <title>ECMA Script</title> </head> <body> <script> const regexp = /t(e)(st(\d?))/g; const str = 'test1test2'; const array = [...str.matchAll(regexp)]; console.log(array); console.log(array); </script> </body> </html>
In this article, we have explained the
matchAll() method and introduced the usage of the method. Also, we have learned the following points:
String.prototype.matchAll()method returns an iterator that represents the matches and allows us to iterate, destructure or transform to an array when needed.
If no matches were found, then
String.prototype.matchAll()method returns a null.
This method considers all matches, including capturing groups in simple usage.
This method throws a TypeError while using non-global regular expression.
After exhausting the iterator, we need to reinvoke
String.prototype.matchAllto iterate once more.