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

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

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

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'.