Home  >  Article  >  Web Front-end  >  How to search for a pattern in a string in JavaScript?

How to search for a pattern in a string in JavaScript?

WBOY
WBOYforward
2023-08-30 12:13:011320browse

In this article, we will search for a specific pattern and pass only the strings that match the given pattern. We will use the following method to implement this functionality -

Method 1

In this method we will search for the string matching the given pattern and get it from the string. string.search() is a built-in method provided by JavaScript for searching strings. We can also pass a regular expression or a normal string in this method.

Syntax

str.search( expression )

Parameters

  • str - Defines the string to be compared.

  • Expression - Defines a string expression that will be compared to a string

This will return a string The index where the string has started to match, or "-1" will be returned if the string does not match.

Example 1

In the following example, we compare a string with a regular expression and return its index if the string matches. If not, -1 will be returned.

#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>

Output

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

Example 2

below In the example, we create multiple regular expressions and check whether they meet the requirements on the string.

# 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 中搜索字符串中的模式?

The above is the detailed content of How to search for a pattern in a string in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete