How to search a string for a pattern in JavaScript?


In this article, we are going to search for a specific pattern and only by pass those string that matches the given pattern. We will be using the following approaches to achieve this functionality −

Approach 1

In this approach, we will be searching for a string that matches the given pattern and find their indexes from the string. The string.search() is an inbuilt method provided by JavaScript for searching a string. We can also pass a regular expression or a normal string in this method.

Syntax

str.search( expression )

Parameters

  • str − defines the string that needs to be compared.

  • expression − defines the string expression with which the string will be compared

This will return the index of the string from where the string has started matching, If the string does not match “-1” will be returned.

Example 1

In the below example, we are comparing a string with a regex expression and returning 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 = '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>

Output

Example 2

In the below example, we have created multiple regex expressions and checked them on the string whether they fulfill the requirements or not.

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

Output

Updated on: 26-Apr-2022

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements