Substr Method in JavaScript

The substr method in JavaScript is a powerful tool for extracting a portion of a string. It allows you to specify a starting index and a length, and it returns the substring that begins at the specified index and extends for the given number of characters. This method is particularly useful when you need to obtain specific parts of a string based on their position.

How substr Works

The substr method takes two arguments:

  1. Starting Index: The position in the string where the extraction begins. Note that JavaScript uses zero-based indexing, meaning the first character of the string is at position 0.
  2. Length: The number of characters to extract from the string.

Example Usage

Consider the following example, which demonstrates how to use the substr method to extract a substring:

Listing 7.8. Finding substrings (http://jsbin.com/mesisi/edit?js,console)

var message = "We choose to go to the Moon!";

console.log(message.substr(3, 12));

In this example, the substr method is used to extract a substring from the message string. It starts at index 3 and extracts 12 characters, resulting in the output:

> choose to go

Using indexOf with substr

The indexOf method can be combined with substr to dynamically find and extract parts of a string. For instance, you can use indexOf to locate the position of a specific character or substring and then use substr to extract a portion of the string starting from that position.

Listing 7.9. Finding a character with indexOf (http://jsbin.com/bidabi/edit?js,console)

var message = "The cow jumped over the Moon!";

var charIndex = message.indexOf("M");

console.log(message.substr(charIndex, 3));

In this example, indexOf is used to find the position of the character "M" in the message string. The substr method then extracts a substring of length 3 starting from that position, resulting in the output:

> Moo

This demonstrates how substr can be used in conjunction with other string methods to perform more complex string manipulations.