Skip to content
Related Articles

Related Articles

Improve Article

Javascript String matchAll() Method

  • Last Updated : 25 Mar, 2021
Geek Week

In Javascript, the matchAll() method is used to return all the iterators matching the reference string against a regex (regular expression). An important use of the matchAll() method is that it can be used to capture groups with the /g flag giving it an advantage over the match() method which ignores capturing groups with the /g flag.

Syntax:

str.matchAll(Regexp)
  • str: It is the reference string for which matches are to be found.
  • Regexp: It is simply a regular expression object. The RegExp object must include the /g flag, else an TypeError is thrown.
  • Return value: It is an iterator.

Example :

HTML




<html>
<body>
<script
function myFunction() { 
    
    //Regular expression with the /g flag
    const regex = /e(xam)(ple(\d?))/g;
    //Reference string
    const str = 'example1example2example3';
      
    //Using matchAll() method
    const array = [...str.matchAll(regex)];
      
    console.log(array[0]);
    console.log(array[1]);
    console.log(array[2]);
}  
myFunction(); 
</script
  </body>
</html>

Output:           

In the above example, we were able to find matches and also capture the internal groups as we used the matchAll() method. 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!

My Personal Notes arrow_drop_up
Recommended Articles
Page :