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>

當我們執行指令碼時,它將在網頁上顯示文字。

廣告