JavaScript Code

JavaScript String search()

String search()
  • 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. search is case sensitive


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