Signup/Sign In

Javascript ES11 matchAll() Function

The 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.

Syntax for matchAll():

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.

Example: Applying String.prototype.matchAll() method

In this example, we have demonstrated how we can find the matches using regular expression also captured the internal groups with the help of matchAll() method.

<!DOCTYPE html>
	<title>ECMA Script</title>
	const regexp = /t(e)(st(\d?))/g;
	const str = 'test1test2';
	const array = [...str.matchAll(regexp)];


Javascript String matchAll() method


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.matchAll to iterate once more.

About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight