JavaScript String indexOf()
Summary: in this tutorial, you’ll learn how to use the JavaScript String indexOf()
method to find the index of a substring within a string.
The String.prototype.indexOf()
returns the index of the first occurrence of substring (substr
) in a string (str
):
let index = str.indexOf(substr, [, fromIndex]);
Code language: JavaScript (javascript)
It returns -1 if the str
does not contain the substr
.
The fromIndex
is an optional parameter that specifies the index at which the search starts. It defaults to zero (0), meaning that if you omit the fromIndex
, the search will start from the beginning of the string.
The indexOf()
always perform a case-sensitive search.
To find the index of the last occurrence of a substring in a string, you use the lastIndexOf()
method.
JavaScript String indexOf() examples
Let’s take some examples of using the indexOf()
method.
1) Using indexOf()
method example
The following example uses the indexOf()
to get the index of the first occurrence of the substring 'str'
in the string 'finding substring in string'
:
let str = 'finding substring in string';
let index = str.indexOf('str');console.log(index); // 11
Code language: JavaScript (javascript)
2) Using indexOf()
to count occurrences of a substring in a string
The following example uses the indexOf()
method to count the number of occurrences of the substring 'know'
in the string 'You do not know what you do not know until you know.'
:
let str = 'You do not know what you do not know until you know.';
let substr = 'know';let count = 0;
let index = str.indexOf(substr);
while(index !== -1) {
count++;
index = str.indexOf(substr, index + 1);
}
console.log(count);
Code language: JavaScript (javascript)
How it works:
- First, use the
indexOf()
method to find the first occurrence of thesubstr
in thestr
. - Then, use the
while
loop to repeatedly find the next position of thesubstr
in thestr
starting from the last found position + 1.
3) The indexOf() and case-sensitivity
The indexOf()
is case-sensitive. See the following example:
let str = 'JS indexOf';
let substr = 'js';let index = str.indexOf(substr);
console.log(index); // -1
Code language: JavaScript (javascript)
In this example, the indexOf()
returns -1 because the string JS IndexOf
does not contain the substring js
but JS
.
To perform a case-insensitive search for the index of a substring within a string, you can convert both substring and string to lowercase before using the indexOf()
method as follows:
let str = 'JS indexOf';
let substr = 'js';let index = str.toLocaleLowerCase().indexOf(substr.toLocaleLowerCase());
console.log(index); // 0
Code language: JavaScript (javascript)
Summary
- The
indexOf()
returns the index of the first occurrence of a substring in a string, or -1 if the string does not contain the substring. - The
indexOf()
is case-sensitive.