If we want to know the index number of the last occurrence of a value in a string, we can use the `lastIndexOf()` method.
For example, let’s say we have a sentence like “My name is John and my last name is Doe”. Now here, if we want to find the location of the last occurrence of the word “name”, we can use the `lastIndexOf()` method.
Another way of thinking about this method is to say, the method starts from the end of a string value and moves back towards the beginning of that string, looking for the specified substring value.
String lastIndexOf() Method Parameters:
The lastIndexOf() method takes two arguments:
- The first argument is the substring value that we want to look for in the target string.
- The second argument is the location from which we want this search to start. This value is optional and, if omitted, the default value is the index number of the last character of that string (This number is equal to the length of that string).
String lastIndexOf() Method Return Value:
The method returns the index number of the last occurrence of the value.
- If the value does not exist in the target string, the return value will be -1.
- The method is case sensitive. So if you’re looking for a word like “name” but in the target string we had “Name” with the first character being capital, then the return value will be -1.
const message = "Me and you and the other people like you and me!" console.log(message.lastIndexOf("and")); console.log(message.lastIndexOf("you"));