In this blog post, we will delve into the intricacies of the JavaScript lastIndexOf() method for strings.
The lastIndexOf() method is used to determine the position of the last occurrence of a specified string within another string. It takes a search string as a parameter and returns the index of the last occurrence. If the search string is not found, it returns -1.
Let’s take a look at a couple of examples to understand how this method works:
'JavaScript is a great language. Yes I mean JavaScript'.lastIndexOf('Script') // Returns 47
'JavaScript'.lastIndexOf('C++') // Returns -1
In the first example, we search for the string ‘Script’ within the given sentence. Since it appears the second time at index 47, the lastIndexOf() method returns 47.
In the second example, the search string is ‘C++’, which is not present in the given string ‘JavaScript’. Hence, the lastIndexOf() method returns -1.
It is worth noting that the lastIndexOf() method is case-sensitive. So, ‘Script’ and ‘script’ would be treated as distinct strings.
To gain a better understanding of this topic, you may also want to explore the indexOf()
method, which is closely related to lastIndexOf().
Tags: javascript, string methods, lastIndexOf()