如何在 JavaScript 中搜索字串中的模式?
在本文中,我們將搜尋特定的模式,並且只通過那些與給定模式匹配的字串。我們將使用以下方法來實現此功能:
方法 1
在這種方法中,我們將搜尋與給定模式匹配的字串,並從字串中找到它們的索引。string.search() 是 **JavaScript** 提供的用於搜尋字串的內建方法。我們還可以在此方法中傳遞正則表示式或普通字串。
語法
str.search( expression )
引數
str - 定義需要比較的字串。
expression - 定義將與字串進行比較的字串表示式
這將返回字串從哪裡開始匹配的索引,如果字串不匹配,則將返回“-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 = 'Start your learning journey with tutorials point today!'; // 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>
輸出
示例 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 = 'Start your learning journey with tutorials point today!'; // 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>
輸出
廣告