JavaScript Code

JavaScript String search()

String search()

In JavaScript, method is used to find the index of the first occurrence of the search string in the string, or the index of first substring that matches the given regular expression.



  • str is a string.
  • search is function name.
  • searchValue is a string. regular string or regular expression.

search() method returns the index/position of the first occurrence of the string searchValue in the string str . If the string searchValue is not found in string str, the function returns -1.


1. Find index of 'banana' string, in string variable str.

let str = 'apple banana mango banana';
let index ='banana');

2. Find index of 'banana' string in string variable str. The search value is absent in the string str. Therefore the function returns a value of -1.

let str = 'apple mango cherry';
let index ='banana');

3. find index of 'banana' as case insensitive using regular expression

let str = 'apple Banana mango banana cherry';
let index =;

When case is not considered Banana matches with banana, therefore search() returns the index of Banana.

Copyright @2022