JavaScript indexOf() method
The indexOf()
method in JavaScript is used to determine the index of the first occurrence of a specified substring (search value) within a string. If the substring is not found, it returns -1
. This method is case-sensitive and can also accept an optional starting position from which to begin the search.
Syntax:
searchValue
: The substring you want to search for within the string.fromIndex
(optional): An integer that specifies the index at which to start the search. If omitted, the search starts from index0
(the beginning of the string).
Return Value:
- It returns the zero-based index of the first occurrence of
searchValue
within the string. If the substring is not found, it returns-1
.
Example 1: Basic Usage
In this example, the substring "world"
starts at index 7
in the string "Hello, world!"
.
Example 2: Case Sensitivity
The indexOf()
method is case-sensitive. This means that searching for "hello"
will not match "Hello"
.
Example 3: Using fromIndex
You can specify a starting position for the search using the fromIndex
parameter. The search begins at the specified index and continues to the end of the string.
Example 4: Not Finding the Substring
If the specified substring is not found within the string, indexOf()
will return -1
.
Example 5: Finding Empty Strings
When searching for an empty string (""
), indexOf()
will return 0
, because an empty string is found at the beginning of any string.
Example 6: Finding the Last Occurrence
If you need to find the last occurrence of a substring, you should use the lastIndexOf()
method, which searches from the end of the string backwards.
Summary:
- The
indexOf()
method finds the index of the first occurrence of a specified substring within a string and returns-1
if not found. - It is case-sensitive and can take an optional
fromIndex
argument to specify where to start searching. - Searching for an empty string returns
0
, as an empty substring is considered to be at the start of any string. - For finding the last occurrence of a substring, use the
lastIndexOf()
method instead.