JavaScript String lastIndexOf() Method

JavaScript String lastIndexOf() Method

As the name of the method says it all, the method lastIndexOf, is going to return the index of the last occurrence of some string inside a string. Also, if the string is not at all present in the given string, then -1 is the return value here.

Now, we are going to have a look at an example, which gives us some idea about the method, which is lastIndexOf. We have to give a string as an argument, and it gives the last index of occurrence of the string in the given string.

This is like we are calling the method, and saying that – hey lastIndexOf, take this string, and return the last index of occurrence of the string in the given string. Have a look at the below program, and get the idea, of how we can use the string method lastIndexOf.

As you can see, we are using the lastIndexOf method and passing the string as an argument. It returns the last occurrence index of the given string in the string. Lets now have a look at the output –

As you can see, the output comes out to be 25, which is the last occurrence index of the string provided as an argument to the method lastIndexOf.

Now, let’s have a look at another case, where the string that we are searching for the last index of, is not present at all, in the given string. Let’s have a look at the program now –

As you can see, we gave such a string, which is not at all present in the given string, and as the result, we got -1 as an output.

As you can see, the output comes out to be -1. This is the lastIndexOf method, which returns the last occurrence index of the given string, in the string. Remember that the method returns the last occurrence index, and if the string does not occur in the given string, then -1 is returned.