The indexOf() method in JavaScript is used to find the index of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.
Syntax: string.indexOf(searchValue, startIndex)
- searchValue: The substring to search for within the string.
- startIndex (optional): The index at which to begin the search. If omitted, the search starts at index 0.
Example:
let str = "Hello, World!";
let index = str.indexOf("World");
console.log(index); // Output: 7
Explanation:
- We have a string str containing "Hello, World!".
- We use indexOf("World") to find the index of the first occurrence of "World" within the string.
- The method returns 7 because "World" starts at index 7 in the string.
Code Compiler Link: https://app.singhteekam.in/codecompiler/