Javascript String search()

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

Example

let sentence= "I love JavaScript.";

// pattern that searches the first occurence of an uppercase character
let regExp = /[A-Z]/;

// searching for a match between regExp and given string let indexReg = sentence.search(regExp);
console.log(indexReg); // Output: 0

search() Syntax

The syntax of the search() method is:

str.search(regexp)

Here, str is a string.


search() Parameters

The search() method takes a single parameter:

  • regExp - A regular expression object (Argument is implicitly converted to regExp if it is a non-regExp object)

search() Return Value

  • Returns the index of the first match between the regular expression and the given string
  • Returns -1 if no match was found.

Example 1: Using search() Method

// defining string
let string1 = "JavaScript JavaScript1";

// pattern having 'JavaScript' followed by a digit
let regExp = /(JavaScript)\d/;

// searching for a match between regExp and given string let index = string1.search(regExp);
console.log(index);

Output

11

In the above example, we have used the search() method to search for a match between the regular expression and the given string.

Here regExp indicates a pattern having 'JavaScript' followed by a digit.

string1.search(regExp) executes the search and returns 11 which is the index value of the match found i.e.'JavaScript1'.


Example 2: Passing non-regExp in search()

let string1 = "I love to code in JavaScript.";

// searching word "JavaScript" in the given string let index = string1.search("code");
console.log(index);

Output

10

In the above example, we have passed a non-regular expression 'code' in the search() method.

The method converts 'code' into regExp implicitly and performs a search in the given string.

string1.search("code") returns 10 which is the index of 'code'.


Recommended Reading: JavaScript String match()