JavaScript String search() 方法



JavaScript String 的search()方法在原始字串中搜索字串或正則表示式,並返回第一個匹配項的索引(位置)。如果未找到匹配項,則返回-1

此方法區分大小寫,這意味著它將字串“Hi”和“hi”視為兩個不同的值。但是,您可以透過在正則表示式中使用/i標誌使search()方法不區分大小寫

注意 - 正則表示式的'g'(全域性)標誌對search()方法的結果沒有影響,並且搜尋始終像regexp lastIndex為0一樣發生。

語法

以下是 JavaScript String search()方法的語法 -

search(regexp)

引數

  • regexp - 一個regexp(正則表示式)物件。

返回值

此方法返回regexp與給定字串之間第一個匹配項的索引(位置)。

示例 1

如果在regexp和原始字串之間找到匹配項,則此方法將返回第一個匹配項的索引。

在以下程式中,我們使用 JavaScript String 的search()方法來匹配和檢索regexp“/point/i”在原始字串“Welcome to Tutorials Point”中的索引(或位置)。

<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script>
   const str = "Welcome to Tutorials Point";
   document.write("Original String: ", str);
   let regexp = /point/i;
   document.write("<br>regexp: ", regexp);
   document.write("<br>The sub-string '", regexp, "' found at position ",str.search(regexp));
</script>    
</body>
</html>

輸出

上述程式將字串“Point”的索引(位置)返回為21。

Original String: Welcome to Tutorials Point
regexp: /point/i
The sub-string '/point/i' found at position 21

示例 2

如果在原始字串中未找到指定的regexp,則search()方法將返回-1

以下是 JavaScript String search()方法的另一個示例。在此示例中,我們使用此方法來匹配regexp“/Hi/”在原始字串“Hello World”中。

<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("Original String: ", str);
   let regexp = /Hi/;
   document.write("<br>regexp: ", regexp);
   document.write("<br>The regexp '", regexp, "' found at position ",str.search(regexp));
</script>    
</body>
</html>

輸出

執行上述操作後,它將返回-1。

Original String: Hello World
regexp: /Hi/
The regexp '/Hi/' found at position -1

示例 3

讓我們在條件語句中使用方法結果來檢查regexp“/[^\w\P']/;”與原始字串“Tutorials Point”之間是否找到匹配項。

<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("Original String: ", str);
   let regexp = /[^\w\P']/;
   document.write("<br>regexp: ", regexp);
   let index = str.search(regexp);
   document.write("<br>Method returns: ", index, "<br>");
   if(index !=-1){
      document.write("Match found");
   }
   else{
      document.write("Not found");
   }
</script>    
</body>
</html>

輸出

以下是上述程式的輸出 -

Original String: Tutorials Point
regexp: /[^\w\P']/
Method returns: 9
Match found
廣告