What is the String search() Method in JavaScript?

The search() method in JavaScript searches for a match between a string and a regular expression.

Syntax

The search() method can be declared as shown in the code snippet below:

string.search(regExp);
  • regExp: A regular expression object.

If a non-RegExp object is passed, it is implicitly converted to a RegExp object.

Return value

The search() method returns the position of the first match.

The search() method returns -1 if there is no match found.

Examples

Example 1

Consider the code snippet below, which demonstrates the use of the search() method.

var str = "Hello world!! This is Educative";
if ( str.search(/world/) != -1 ) {
console.log("str contains world." );
} else {
console.log("str does not contains world." );
}

Explanation

A string str is declared in line 1. The search() method is used in line 3 to check if str contains the word "world".

Example 2

A string is a non-RegExp object. If it is passed to the search() method, it is first converted to a RegExp object. Consider the code snippet below, which demonstrates the use of the search() method with a string.

var str = "Hello world!! This is Educative";
if ( str.search("world") != -1 ) {
console.log("str contains world." );
} else {
console.log("str does not contains world." );
}

Explanation

A string str is declared in line 1. The search() method is used in line 3 to check if str contains the word "world".

Free Resources