Finding a Character's Index Position Using indexOf() and lastIndexOf()






string.indexOf("character value")
string.lastIndexOf("character value")

Opposite of charAt(), indexOf() returns the index position of any character you specify as the parameter.

*****If no match is found, a value of -1 is returned.***** This is a powerful tool to use if you need to search for an instance of a character.

lastIndexOf() returns the index position of any character you specify as the parameter, except it begins the search at the end of a string and works its way backward. Very handy!

Both methods have an optional 2nd parameter that allows you to specify where in the string to begin the search. For instance, if you want to look for an occurance of the letter "y" starting at position 5, the syntax would be: indexOf("y",5)

View the Source


 


View Source | Home | Contact