lastIndexOf()

The lastIndexOf() method is used to return the character position (or index) of the string (defined by stringToSearchFor, in parentheses) passed as its parameter. Another parameter which can be used is the numberOfTimesToIgnore (see syntax) parameter, which specifies the number of instances of stringToSearchFor to ignore before reporting its place in the string. If the indexOf() method does not find a match to the string given, a value of -1 will be returned. Examine the syntax and especially the example to get a feel for what this method can accomplish.

syntax:

stringName.lastIndexOf(stringToSearchFor)

stringName.lastIndexOf(stringToSearchFor, numberOfTimesToIgnore)

EXAMPLE

var newString = new String("This is the string of text.");

document.write("The word 'the' is first encountered at position " + newString.lastIndexOf("the") )

The example shows a new string being created called newString. A document.write statement then writes some applicable descriptive text to the screen along with the position of the first encountered instance of the word "the". The ouput should look like the following:



The word 'the' is first encountered at position 8



If the stringToSearchFor is a letter or string that is not within the referenced string object, then a value of -1 would be returned. For example, if you were to assign stringToSearchFor as the letter "a", which is not within the string, the value returned would be as follows:



The letter 'a' is first encountered at position -1