Javascript String search()

The JavaScript String search() method searches the string for a value specified by a regular expression.

The syntax of the search() method is:

str.search(regexp)

Here, str is a string.


search() Parameters

The search() method takes in:

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

Return value from search()

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

Example: Using search()

const string = "I love to write JavaScript programs";

let re = /[a-z]/;
let index = string.search(re);
console.log(index); // 2 -> matches 'l'

let re1 = /J[a-z]*/i;
let index1 = string.search(re1);
console.log(index1); // 16 -> matches 'JavaScript'

let re2 = /[0-9]/;
let index2 = string.search(re2);
console.log(index2); // -1 -> No digit match

Output

2
16
-1

Recommended Reading: JavaScript String match()