steave
answered Feb 25 '23 00:00
The JavaScript String.indexOf() method is used to find the index of the first occurrence of a specified substring within a string. Here's how you can use it:
Syntax:
string.indexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex (optional): The index to start the search from. If omitted, the search starts at index 0.
Return Value:
The index of the first occurrence of the specified substring within the string. If the substring is not found, it returns -1.
Example:
const sentence = "The index of the first occurrence of the specified substring ";
const index = sentence.indexOf("of");
console.log(index); // Output: 10
In the example above, the indexOf() method is used to find the index of the substring "fox" in the sentence string. The method returns the index 16, which is the position of the first occurrence of "fox" in the string.