The lastIndexOf() method in JavaScript is similar to indexOf(), but it returns the index of the last occurrence of a specified substring within a string. If the substring is not found, it returns -1.
Syntax: string.lastIndexOf(searchValue, startIndex)
- searchValue: The substring to search for within the string.
- startIndex (optional): The index at which to begin the search. If omitted, or if it's greater than or equal to the string length, the entire string will be searched.
Example:
let str = "Hello, World, World!";
let lastIndex = str.lastIndexOf("World");
console.log(lastIndex); // Output: 13
Explanation:
- We have a string str containing "Hello, World, World!".
- We use lastIndexOf("World") to find the index of the last occurrence of "World" within the string.
- The method returns 13 because the last occurrence of "World" starts at index 13 in the string.
Code Compiler Link: https://app.singhteekam.in/codecompiler/