JavaScript - Symbol.search 屬性



在 JavaScript 中,Symbol.search 屬性是一個特殊的符號值,用作知名符號的鍵。此符號用作物件上的屬性鍵,以定義在字串中搜索的自定義行為。它主要與正則表示式和 String.prototype.search() 方法結合使用。

當 Symbol.search 屬性用作物件上的方法時,它定義了在呼叫其 search() 方法時物件的行為。預設情況下,search() 方法在字串中搜索指定的值,並返回第一次出現的位置索引,如果找不到該值,則返回 -1。

語法

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

[Symbol.search](string)

引數

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

返回值

此屬性返回字串匹配的位置,如果未找到匹配項,則返回“-1”。

示例

示例 1

讓我們來看下面的例子,我們將建立一個使用 Symbol.search 的自定義方法的物件。

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

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

示例 2

考慮另一種情況,我們將使用 Symbol.search 和自定義類。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x {
            constructor(value) {
               this.value = value;
            }
            [Symbol.search](string) {
               return string.indexOf(this.value);
            }
         }
         const a = new x('EveryOne');
         document.write('Welcome EveryOne'.search(a));
      </script>
   </body>
</html>

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

示例 3

在下面的示例中,我們將返回“-1”,如果未找到匹配項。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const a = "   Welcome To The TutorialsPoint";
         const x = /is/;
         Symbol.search = function(string, pattern) {
            const index = string.indexOf(x);
            return index === -1 ? -1 : index;
         };
         document.write(a.search(x));
      </script>
   </body>
</html>

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

示例 4

以下是一個示例,我們將使用正則表示式並執行匹配。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            [Symbol.search](string) {
               const regex = /The/;
               return regex.exec(string).index;
            }
         };
         const str = "Welcome To The World";
         document.write(str.search(x));
      </script>
   </body>
</html>

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

廣告