The JavaScript string object contains an lastIndexOf method. It returns the index in the string of the last occurrence of a specified character. The index is numbered starting at 0. For example:
var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('t'));
The index returned in the preceding example is 14, as there are 15 characters in the string, “t” is the last character and the index is numbered starting at 0.
The lastIndexOf method accepts an optional second argument – the position at which to begin the search.
var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('j'));
In this example the index returned is 5. Since the search starts at the end of the string and works backwards it finds the last “j”, which is at position 5 in the string. If we tell the string to start looking backwards from the second position, however, the value returned will be the “j” at position 0, as follows:
var strTest = 'joey javascript';
document.write(strTest.lastIndexOf('j',2));
Related articles:
JavaScript String Object indexOf method