Get Programming with JavaScript - Listing 7.09
Listing 7.09 - Finding a character with indexOf
var message = "We choose to go to the Moon!";
var charIndex = message.indexOf("M");
console.log(message.substr(charIndex, 3));
Further Adventures
Listing 7.09 - Finding a character with indexOf - Task 1
- Use indexOf to find the index of where the word 'go' starts in the message string.
var message = "We choose to go to the Moon!";
var charIndex = message.indexOf("g");
As the g in 'go' is the only one, you can just search for 'g'.
Listing 7.09 - Finding a character with indexOf - Task 2
- Use indexOf and substr to display the word 'choose' from the message string.
var message = "We choose to go to the Moon!";
// Find where the word starts
var charIndex = message.indexOf("c");
// Display 6 letters - the whole word
console.log(message.substr(charIndex, 6));
Listing 7.09 - Finding a character with indexOf - Task 3
- Use lastIndexOf to find the index of the 'oo' in the word 'Moon' of the message string.
var message = "We choose to go to the Moon!";
var charIndex = message.lastIndexOf("oo");
Both 'choose' and 'Moon' include the string 'oo'. lastIndexOf will find the last one in the message, i.e. the 'oo' in 'Moon'.