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:

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 =;
console.log(index); // 2 -> matches 'l'

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

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



Recommended Reading: JavaScript String match()

Did you find this article helpful?