Jump to content
Larry Ullman's Book Forums

Indexof() Method -Absolute Beginner Question


Recommended Posts

Dear Larry,

 

On page 114 you introduced the indexOf() and lastIndexOf() method.  At the bottom of the page you defined the variable fullName as 'Larry Ullman' then gave the following examples:

 

var fullName = 'Larry Ullman';

 

fullName.indexOf('a'); // 1  ( I understand this one)

 

fullName.lastIndexOf('a'); // 10 (I do not understand why you get 10?)

 

I don't understand why it is 10?  Shouldn't it be 1?  If the search is backward, shouldn't it be 1? 

 

Also, since the string 'Larry Ullman' has two a's, does that mean that the lastIndexOf() method will give only the value of the first 'a' that it finds? 

 

This is probably a really stupid question but I am an absolute beginner who is just griding through your book.  So far I really enjoy it.  I figured it would be hard but I'm having fun reading it and going through the examples.

 

thanks in advance,

 

Sid9000K

 

 

 

Link to comment
Share on other sites

lastIndexOf method returns the position of the LAST occurrence of the string that you specify with the argument. In this example, there are 2 a's so the method returns the position of the last one, just before the 'n'.

 

The method works by starting its search at the end of the string for efficiency purposes, but the index that is returned is counted from the beginning of the string (starting from 0).

 

Hope that helps.

  • Upvote 2
Link to comment
Share on other sites

 Share

×
×
  • Create New...