String indexOf()
str.indexOf(search, start)
str
is a stringsearch
is a stringstart
is an integer, index position
indexOf() method returns the index/position of the first occurrence of search
string in the string str
. if start
is provided, the string str
from the start
position is considered for searching
Examples
1. find index of 'le'
search string, in string variable name
let name = 'apple';
let index = name.indexOf('le');
console.log(index);
2. find index of 'an'
search string in string variable name
from a start
position of 10
let name = 'apple banana cherry banana mango';
let start = 10;
let index = name.indexOf('an', start);
console.log(index);
the first occurrence is ignored because the search happens from a start position of 10
3. find index of 'ba'
search string in string variable name
let name = 'apple';
let index = name.indexOf('ba');
console.log(index);
since there is no occurrence of search string in the calling string, indexOf()
returns -1