Description
The JavaScript method indexOf() returns the index of the first occurrence of a specific substring in a string.
The index value that it returns can extend from 0 to str.length - 1.
Syntax
The method checks if the string str contains the substring searchString from index fromIndex to end of the string str.
str.indexOf(searchString, fromIndex)
Parameters
The method accepts the below parameters.
searchString
- It is the string to be searched for within the string
str.
fromIndex (optional)
- It is the index within
strto begin searching forsearchString. - The default value is 0.
Result
The method returns the index of the first occurrence of searchString if found in str, otherwise returns -1.
Example 1: Using the Method
The method returns the index of the first occurrence of a substring in a string.
var str = "Programming languages JavaScript and Java are not the same";
// Finding the index of the first occurrence of "Java"
document.write(str.indexOf("Java")); // Prints: 22
// Finding the index of the first occurrence of empty string
document.write(str.indexOf("")); // Prints: 0
// Finding the index of the first occurrence of "HTML"
document.write(str.indexOf("HTML")); // Prints: -1
Output:
22
0
-1
Example 2: Using the Method with From Index
For a non-integer (or floating-point) index value, the method returns the character from the index determined by ignoring the decimal digits.
var str = "Programming languages JavaScript and Java are not the same";
// Searches for "Java" from index 20
document.write(str.indexOf("Java", 20)); // Prints: 22
// Searches for "Java" from index 30
document.write(str.indexOf("Java", 30)); // Prints: 37
// Searches for "Java" from index 40
document.write(str.indexOf("Java", 40)); // Prints: -1
Output:
22
37
-1
Example 3: Finding All the Occurrences of an Element
We can use loops to iterate over the string multiple times to find all the occurrences of an element.
function findAllIndex(string, value) {
indices = [];
var currentIndex = string.indexOf(value);
while (currentIndex != -1) {
indices.push(currentIndex);
currentIndex = string.indexOf(value, currentIndex + value.length);
}
return indices;
}
var str = "Programming languages JavaScript and Java are not the same";
document.write(findAllIndex(str, "Java")); // Prints: [ 22, 37 ]
document.write(findAllIndex(str, "HTML")); // Prints: []
Output:
[ 22, 37 ]
[]
Overall
The JavaScript method indexOf() returns the index of the first occurrence of a specific substring in a string.