首頁  >  文章  >  web前端  >  如何在 JavaScript 中搜尋字串中的模式?

如何在 JavaScript 中搜尋字串中的模式?

WBOY
WBOY轉載
2023-08-30 12:13:011319瀏覽

在本文中,我們將搜尋特定模式,並且僅傳遞與給定模式相符的字串。我們將使用以下方法來實現此功能 -

#方法 1

在這種方法中,我們將搜尋與給定模式匹配的字串,並從細繩。 string.search() 是 JavaScript 提供的用於搜尋字串的內建方法。我們也可以在此方法中傳遞正規表示式或普通字串。

語法

str.search( expression )

參數

  • #str - 定義需要比較的字串。

  • 表達式 - 定義將與字串進行比較的字串表達式

這將傳回字串的索引,其中字串已開始匹配,如果字串不匹配,將返回“-1”。

範例 1

在下面的範例中,我們將字串與正規表示式進行比較,如果字串符合則傳回其索引。如果沒有,將返回-1。

#index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      Creating Objects from Prototype
   </title>
</head>
<body>
   <h2 style="color:green">
      Welcome To Tutorials Point
   </h2>
</body>
   <script>
      const paragraph = &#39;Start your learning journey with tutorials point today!&#39;;
      // any character that is not a word character or whitespace
      const regex = /(lear)\w+/g;
      console.log("Index: " + paragraph.search(regex));
      console.log("Alphabet start: " + paragraph[paragraph.search(regex)]);
      // expected output: "."
   </script>
</html>

輸出

如何在 JavaScript 中搜索字符串中的模式?

#範例2

#在下面的範例中,我們建立了多個正規表示式,並在字串上檢查它們是否符合要求。

# index. html

<!DOCTYPE html>
<html>
<head>
   <title>
      Creating Objects from Prototype
   </title>
</head>
<body>
   <h2 style="color:green">
      Welcome To Tutorials Point
   </h2>
</body>
   <script>
      const paragraph = &#39;Start your learning journey with tutorials point today!&#39;;
      // any character that is not a word character or whitespace
      const regex = /(lear)\w+/g;
      const regex1 = /(!)\w+/g;
      const regex2 = /(!)/g;
      console.log("Index: " + paragraph.search(regex));
      console.log("Index: " + paragraph.search(regex1));
      console.log("Index: " + paragraph.search(regex2));
      console.log("Alphabet start: " + paragraph[paragraph.search(regex)]);
      // expected output: "."
   </script>
</html>

輸出

如何在 JavaScript 中搜索字符串中的模式?

#

以上是如何在 JavaScript 中搜尋字串中的模式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除