• JavaScript Video Tutorials

JavaScript - Symbol.matchAll Property



One popular JavaScript symbol that was added in ES6 is the Symbol.matchAll property. It functions as the symbol object's key.

The Symbol.matchAll property is used to create an object that represents a regular expression match, which can be iterated over to retrieve all matches in a string. When working with global regular expressions, which match numerous instances of a pattern in a string, this property is very helpful.

Syntax

Following is the syntax of JavaScript Symbol.matchAll property −

regExp[Symbol.matchAll](str);

Parameters

This property takes a string that is used to find matches of the regular expression.

Return value

This property returns an iterator that returns an regular expression matches.

Examples

Example 1

Let's look at the following example, where we are going to use the for of loop to iterate over the matches.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = 'Tutorials, Point';
         const reg_exp = /([A-Z])\w+/g;
         for (const match of x.matchAll(reg_exp)) {
            document.write(match[1] + " < br > ");
         }
      </script>
   </body>
</html>

If we execute the above program, it will displays the text on the webpage.

Example 2

Consider the another scenario, where we are going to use the Array.from to convert the iterator to an array.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = 'HELLO , everyone';
         const reg_exp = /[A-Z]/g;
         const a = Array.from(x.matchAll(reg_exp), m => m[0]);
         document.write(JSON.stringify(a));
      </script>
   </body>
</html>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to use the flags and retturn an iterator of all matched substrings, regardless of case.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const str = 'TutorialsPoint, TP';
         const regex = /tp/gi;
         const matches = str.matchAll(regex);
         for (const match of matches) {
            document.write(match[0]);
         }
      </script>
   </body>
</html>

When we execute the script, it will displays a text on the webpage.

Advertisements