Finding the Index of a Substring in a String
String indexOf: String.indexOf()
The indexOf()
method in JavaScript is used to find the index of the first occurrence of a specified substring within a string.
Syntax:
The parameters
-
searchValue: The substring to search for within the original string.
-
startIndex (optional): The index at which to start the search. If not specified, the search starts from the beginning of the string.
Return Value:
The indexOf()
method returns an integer representing the index of the first occurrence of the specified substring. If the substring is not found, it returns -1
.
Example
In the example above, The indexOf()
method is used to find the index of the first occurrence of the substring βworldβ within the original string str. The resulting index, 7
, is stored in the variable index.
In the example above, The indexOf()
method is used to find the index of the first occurrence of the character βoβ within the original string str. The search starts from index 5
. The resulting index, 8
, is stored in the variable index.
In the example above, The indexOf()
method is used to find the index of the first occurrence of the substring βuniverseβ within the original string str. Since βuniverseβ is not present in the string, the method returns -1
, which is stored in the variable index.
By using the String.indexOf()
method, you can efficiently determine the position of a specified substring within a given string, allowing for various string manipulation operations in JavaScript.