JavaScript で文字列内のパターンを検索するにはどうすればよいですか?

WBOY
リリース: 2023-08-30 12:13:01
転載
1319 人が閲覧しました

この記事では、特定のパターンを検索し、指定されたパターンに一致する文字列のみを渡します。この機能を実装するには、次のメソッドを使用します。

メソッド 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 = &#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>
ログイン後にコピー

output

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

以上がJavaScript で文字列内のパターンを検索するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!