How to Use the String search() Method in JavaScript

08/01/2021

Contents

In this article, you will learn how to use the string search() method in JavaScript.

Using the string search() method in JavaScript

The search() method in JavaScript is used to search for a particular substring within a string and returns the index of the first occurrence of the substring. It is similar to the indexOf() method, but it also allows the use of regular expressions.

Syntax

The syntax of the search() method is as follows:

string.search(regexp)

where string is the string to be searched, and regexp is the regular expression pattern to be searched.

Parameters

The search() method takes only one parameter, which is a regular expression pattern. The pattern can be a string or a regular expression object.

Return value

The search() method returns the index of the first occurrence of the regular expression pattern in the string. If no match is found, it returns -1.

Examples

Here are some examples that demonstrate the use of the search() method:

const str = "The quick brown fox jumps over the lazy dog";

// Search for the string "brown" using a regular expression
const index1 = str.search(/brown/);
console.log(index1); // Output: 10

// Search for the string "quick" using a regular expression
const index2 = str.search(/quick/);
console.log(index2); // Output: 4

// Search for the string "dog" using a regular expression
const index3 = str.search(/dog/);
console.log(index3); // Output: 40

// Search for the string "cat" using a regular expression
const index4 = str.search(/cat/);
console.log(index4); // Output: -1

In the above example, we have defined a string str and used the search() method to search for substrings “brown”, “quick”, “dog”, and “cat” using regular expression patterns.

Using the search() method with variables

The search() method can also be used with variables to search for a substring. Here is an example:

const str = "The quick brown fox jumps over the lazy dog";
const searchStr = "brown";

// Search for the value of searchStr in the string
const index = str.search(searchStr);
console.log(index); // Output: 10

In the above example, we have defined a variable searchStr and used it to search for a substring “brown” in the string str.

Using the search() method with regular expressions

The search() method can also be used with regular expressions to search for a pattern within a string. Here is an example:

const str = "The quick brown fox jumps over the lazy dog";
const searchPattern = /[A-Z]/;

// Search for the first uppercase letter in the string
const index = str.search(searchPattern);
console.log(index); // Output: 0

In the above example, we have defined a regular expression pattern searchPattern to search for the first uppercase letter in the string str. The search() method returns 0 as the first uppercase letter is found at the beginning of the string.