Definition and Usage
The indexOf()
function for strings searches for the specified substring in a string and returns the index of its first occurrence. If the specified substring is not found, it returns -1
.
This function is useful for finding the position of a substring in a string or for checking whether the substring exists.
This function is case-sensitive when searching for strings.
Basic Example
const greeting = "Welcome to codingCourses!";
/*
* Note:
* String indices start at 0.
* The first character has index 0, the second character has index 1.
*/
// Returns the index of the first occurrence of "Welcome" in the greeting string
const hello = greeting.indexOf("Welcome");
console.log(hello); // Output: 0
// Returns -1 because "Nice to meet you" is not found in the greeting string
const niceToMeetYou = greeting.indexOf("Nice to meet you");
console.log(niceToMeetYou); // Output: -1
const coding = greeting.indexOf("coding", 5);
// The second argument specifies the index to start the search from.
// This argument is optional; if omitted, the search starts from index 0.
// Indices are still counted from left to right.
// Since the argument is 5, the search starts from the 6th character.
// The substring "coding" is found starting at index 11, which is the first occurrence from index 5.
console.log(coding); // Output: 11
In arrays, the indexOf()
function for arrays works in the same way.
Syntax
str.indexOf(searchValue[, fromIndex])
str
is the string to which the indexOf()
function is applied.
Parameters
searchValue |
Required. The substring to search for.
Case-sensitive. If no value is provided, the string "undefined" is used as the search target. |
---|---|
fromIndex |
Optional. The 0 -based index at which to start the search.
|
Return Value
The indexOf()
function searches for the specified substring in the target string and returns the index of its first occurrence.
If the specified substring is not found, it returns -1
.
Example with Parameters and Return Values
/*
* If the specified substring appears multiple times in the string,
* the index of the first occurrence is returned.
*/
const str = "The colors are red, blue, blue, and yellow.";
// Returns the index of the first occurrence of "blue" in the str string
const val_1 = str.indexOf("blue");
// There are two occurrences of "blue" in str at indices 14 and 19.
// However, the function returns the index of the first occurrence, which is 14.
console.log(val_1); // Output: 14
// Returns -1 because the substring "green" is not found in the str string
const val_2 = str.indexOf("green");
console.log(val_2); // Output: -1
const val_3 = str.indexOf("e", 1);
// The second argument specifies the index at which to start the search.
// This argument is optional; if omitted, the search starts from index 0.
// Since the argument is 1, the search starts from the second character.
// The first occurrence of "e" from the beginning of the string is at index 2.
console.log(val_3); // Output: 2
//////////////////////////////////////////
const undefinedStr = "A variable with no assigned value is called undefined.";
const val_4 = undefinedStr.indexOf();
// If no value is provided for the first parameter,
// the string "undefined" is used as the search target.
// Returns the index of "undefined", which is 38.
console.log(val_4); // Output: 38
Things to Keep in Mind
The indexOf()
function is case-sensitive when searching for strings.
const redString = "red";
const searchRed = redString.indexOf("Red");
// Uppercase "R" and lowercase "r" are treated differently.
console.log(searchRed); // Output: -1
Practical Examples
Here are several practical uses of the indexOf()
function.
Checking for the Existence of a Substring
You can use the indexOf()
function to check whether a specific substring exists within a string.
If the return value is not -1
, the substring exists.
const str = "Hello, world!";
if (str.indexOf("world") !== -1) {
console.log("The substring exists.");
} else {
console.log("The substring does not exist.");
}
// Output: "The substring exists."
Among the functions for checking the existence of a substring, includes()
is also available. The includes()
function returns true
if the given substring is present in the string, otherwise false
.
Using includes()
is generally more intuitive and convenient than using indexOf()
for checking the presence of a substring.
Case-Insensitive Substring Search
The indexOf()
function is case-sensitive by default, but you can use the toLowerCase()
function to perform a case-insensitive search.
Additional Explanation
The toLowerCase()
function is a method of string objects that converts all characters in the string to lowercase.
const str = "Hello, World!";
const searchStr = "world";
if (str.toLowerCase().indexOf(searchStr.toLowerCase()) !== -1) {
console.log("The substring exists regardless of case.");
}
// Output: "The substring exists regardless of case."
Counting the Number of Occurrences of a Substring
// The target string
const str = "Hello, world! Hello, universe!";
// The substring to search for
const searchStr = "Hello";
let count = 0;
// Find the initial occurrence of the substring
let idx = str.indexOf(searchStr);
// Repeat until no more occurrences are found
while (idx !== -1) {
// Increment the count
count++;
// Search for the next occurrence starting after the previous one
idx = str.indexOf(searchStr, idx + 1);
}
// Output the number of occurrences of the substring
console.log("Number of occurrences of the substring:", count);
// Output: Number of occurrences of the substring: 2
Code Explanation
The while
loop repeatedly executes a block of code as long as the condition evaluates to true
.
In the code above, we use indexOf()
to find the first occurrence of the substring "Hello"
. After that, we call indexOf()
again starting after the previous occurrence to find the next one. We repeat this process, increment the count
for each occurrence, and finally determine the total number of times "Hello"
appears in the string.
Specifications
Specification | |
---|---|
String.prototype.indexOf()
|
ECMAScript Language Specification #sec-string.prototype.indexof |
Compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
---|---|---|---|---|---|
indexOf()
|
1 | 12 | 1 | 1 | 0.10 |