JavaScript Code

JavaScript String search()


String search()

str.search(searchValue)
  • 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

Examples

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

let str = 'apple banana mango banana';
let index = str.search('banana');
console.log(index);

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 = str.search('banana');
console.log(index);

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

let str = 'apple Banana mango banana cherry';
let index = str.search(/banana/i);
console.log(index);

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


Copyright @2022