String search()
In JavaScript, String.search()
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.
Syntax
str.search(searchValue)
where
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
.
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
.