JavaScript - Symbol.replace 屬性



Symbol.replace 屬性用於定義 `String.prototype.replace()` 函式呼叫的方法。當使用子字串或正則表示式作為其初始引數呼叫 `String.prototype.replace()` 時,JavaScript 會在內部搜尋傳遞給它的物件上的 Symbol.replace 屬性。如果檢測到該屬性,則會呼叫此函式以執行替換邏輯。

開發人員可以透過建立自定義 Symbol.replace 方法來操作 JavaScript 應用程式中的字串,從而改變字串替換操作的行為。

語法

以下是 JavaScript Symbol.replace 屬性的語法:

[Symbol.replace](string)

引數

此屬性僅接受一個引數,即字串。

返回值

此屬性返回一個新字串。

示例

示例 1

讓我們來看下面的例子,我們將使用自定義物件和 Symbol.replace。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            [Symbol.replace](string, replace) {
               return string.replace(/To/g, replace);
            }
         };
         const a = "Welcome, To!";
         const y = a.replace(x, "To TutorialsPoint");
         document.write(y);
      </script>
   </body>
</html>

如果執行上述程式,它將在網頁上顯示文字。

示例 2

考慮另一種情況,我們將使用 Symbol.replace 進行日期格式化。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            [Symbol.replace](y) {
               const date = new Date(y);
               return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
            }
         };
         const a = "02-07-2024";
         document.write(a.replace(x));
      </script>
   </body>
</html>

執行上述指令碼後,它將在網頁上顯示文字。

示例 3

在下面的示例中,我們將用 '*' 替換母音。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            [Symbol.replace](str) {
               return str.replace(/[aeiou]/gi, '*');
            }
         };
         document.write('TUTORIALSPOINT'.replace(x));
      </script>
   </body>
</html>

執行指令碼後,它將在網頁上顯示 '*'。

示例 4

以下是一個示例,我們將用其雙倍值替換數字。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            [Symbol.replace](str) {
               return str.replace(/\d/g, match => match * 3);
            }
         };
         document.write('Raju had 3 chocolates and 2 biscuits'.replace(x));
      </script>
   </body>
</html>

執行上述指令碼後,將彈出輸出視窗,在網頁上顯示文字。

廣告