Get Programming with JavaScript - Listing 7.08

Listing 7.08 - Finding substrings

var message = "We choose to go to the Moon!"; console.log(message.substr(3, 12));

Further Adventures

Listing 7.08 - Finding substrings - Task 2

var message = "We choose to go to the Moon!"; console.log(message.substr(3)); // choose to go to the Moon! console.log(message.substr(10)); // to go to the Moon! console.log(message.substr(13)); // go to the Moon!

Omitting the second argument returns the rest of the string from the index specified by the first argument.

Listing 7.08 - Finding substrings - Task 3

var message = "We choose to go to the Moon!"; console.log(message.substr(-3)); // on! console.log(message.substr(-10)); // the Moon!

If the first argument is negative, substr finds its starting index by counting back from the end of the string.

var message = "We choose to go to the Moon!"; console.log(message.substr(3, -3)); // console.log(message.substr(3, -10)); //

If the second argument is negative, substr returns an empty string.