😄 This post is based on the content from coding.courses.
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 performing the search.
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
Syntax
str.indexOf(searchString)
str.indexOf(searchString, position)
str is the string to which the indexOf() function is applied.
Parameters
# searchString
Required. The substring to search for.
Case-sensitive.
If no value is provided, the string "undefined" is used as the search target.
# position
Optional. The 0-based index at which to start the search.
- If omitted, the default value 0 is used.
- Negative values can be used, in which case counting starts from the end of the string. However, the search is still performed from left to right.
- If the value is greater than or equal to the length of the string (str.length), -1 is returned.
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
Practical Examples
# Checking for the Existence of a Substring
ou 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."
# 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.
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
Top comments (0)