JavaScript Tutorials

JavaScript String search()
Syntax & Examples

String.search() method

The search() method of the String class in JavaScript is used to search for a match between a regular expression and the calling string.


Syntax of String.search()

The syntax of String.search() method is:

search(regexp)

This search() method of String search for a match between a regular expression regexp and the calling string.

Parameters

ParameterOptional/RequiredDescription
regexprequiredA regular expression object against which to match the calling string.

Return Type

String.search() returns value of type Number.



✐ Examples

1 Using search() method with a regular expression

In JavaScript, the search() method can be used to search for a pattern within a string using a regular expression.

For example,

  1. We define a string variable str with the value 'The quick brown fox jumps over the lazy dog'.
  2. We use the search() method with a regular expression to search for the pattern 'quick'.
  3. The result is stored in the variable index.
  4. We log index to the console using the console.log() method.

JavaScript Program

const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/quick/);
console.log(index);

Output

4

2 Using search() method with a regular expression and no match

In JavaScript, if no match is found, the search() method returns -1.

For example,

  1. We define a string variable str with the value 'The quick brown fox jumps over the lazy dog'.
  2. We use the search() method with a regular expression to search for the pattern 'cat'.
  3. The result is stored in the variable index.
  4. We log index to the console using the console.log() method.

JavaScript Program

const str = 'The quick brown fox jumps over the lazy dog';
const index = str.search(/cat/);
console.log(index);

Output

-1

Summary

In this JavaScript tutorial, we learned about search() method of String: the syntax and few working examples with output and detailed explanation for each example.