String indexOf()
In JavaScript, String.indexOf()
method is used to find the index of the first occurrence of the search string in the string.
Syntax
str.indexOf(search, start)
str
is a string.search
is a string.start
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
.