Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML Search Methods

LastIndexOf

I am struggling to understand the concept of LastIndexOf()... I have searched other examples and remain mystified. Here are some from MDN:

let anyString = 'Brave new world';

console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// logs 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// logs 10

I would have thought the index of the first w from the end would have been 6! And 10 would have been the 'e' in Brave.

I know I am missing something, any insight would be appreciated!

1 Answer

Michael Cook
Michael Cook
2,125 Points

The String.lastIndexOf(char) method finds the index of the last occurrence of the character you pass to it. String.indexOf(char) finds the first occurrence of the character you pass it. Both these string methods look at the string from left to right, the same way you would read it. Also, the indices of a string work the exact same way as an array - they start at 0 and every character (including spaces) has an index.

So, if you count each character in your string from left to right, you'll see that 8 and 10 make perfect sense.

Don't be afraid to read the MDN docs. I know they can be a bit challenging, but the more you read them the more they will make sense. Hope this answer helps you.

Oh wow! Yes that fully cleared it up thank you! I was definitely misunderstanding. Thanks again!!