JavaScript - Symbol.matchAll 属性



ES6 中添加的一个流行的 JavaScript 符号是 **Symbol.matchAll** 属性。它充当符号对象的键。

Symbol.matchAll 属性用于创建表示正则表达式匹配的对象,可以对其进行迭代以检索字符串中的所有匹配项。在处理全局正则表达式时,该表达式在字符串中匹配模式的多个实例,此属性非常有用。

语法

以下是 JavaScript Symbol.matchAll 属性的语法:

regExp[Symbol.matchAll](str);

参数

此属性采用一个字符串,用于查找正则表达式的匹配项。

返回值

此属性返回一个迭代器,该迭代器返回正则表达式匹配项。

示例

示例 1

让我们看一下下面的示例,我们将使用 for of 循环来迭代匹配项。

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

如果我们执行上述程序,它将在网页上显示文本。

示例 2

考虑另一种情况,我们将使用 Array.from 将迭代器转换为数组。

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

执行上述脚本后,它将在网页上显示文本。

示例 3

在下面的示例中,我们将使用标志并返回所有匹配子字符串的迭代器,而不区分大小写。

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

当我们执行脚本时,它将在网页上显示文本。

广告

© . All rights reserved.