JavaScript lastIndexOf() Method
This tutorial introduces JavaScript's lastIndexOf() method, from the String object. The lastIndexOf() method retrieves the position index of the last instance of a substring in a given string. It offers easy-to-use but limited functionality like the pattern-matching regular expressions available through the JavaScript RegExp object (outside the scope of this tutorial).
The lastIndexOf() method is case-sensitive: a lowercase letter will not produce a match for the search of its uppercase equivalent.
Related string method:
Unlike lastIndexOf(), the indexOf() method matches the first substring match in another string.
Using the lastIndexOf() Method
The lastIndexOf() method follows the same syntax as indexOf():
// Find needle in haystack (two pre-declared strings)
haystack.lastIndexOf(needle);
Both searched-for string and searched-in string can be a declared variable or an anonymous quoted string. The script below demonstrates tries to match a quoted string in a string variable:
var carter = new String("I learn JavaScript.");
// Use lastIndexOf() to find position index of last space
alert( carter.lastIndexOf(" ") );
Our script displays 7, the position of the second (and last) space character.
The lastIndexOf() Method and Failed Matches
The lastIndexOf() method returns a negative one (-1) when no match is found.
var carter = new String("I learn JavaScript.");
alert( carter.lastIndexOf("j") );
Lowercase "j" could not be matched in our string variable; lastIndexOf() could therefore not return a position index: it returned -1.
lastIndexOf() is a case-sensitive: lowercase letters have different values than identical uppercase letters.
You can circumvent this by converting strings with the toLowerCase() or toUpperCase() methods.
Test the lastIndexOf() Method
Interactively test the lastIndexOf() method by editing the JavaScript code below and clicking the Test lastIndexOf() Method button.
Browser support for JavaScript lastIndexOf() method | |||
---|---|---|---|