/

Understanding the JavaScript substring() Method

Understanding the JavaScript substring() Method

The JavaScript substring() method is a useful tool for extracting a portion of a string. Similar to the slice() method, it has some distinct differences that set it apart.

Usage and Syntax

The syntax of the substring() method is as follows:

1
string.substring(startIndex, endIndex)
  • startIndex is the index at which the extraction should begin (inclusive).
  • endIndex is the index at which the extraction should end (exclusive).

Key Differences

There are a few key differences between the substring() method and the slice() method:

  1. Handling of Negative Parameters: If either the startIndex or endIndex parameter is negative, it is automatically converted to 0. This means that the substring extraction will start from the beginning of the string.
  2. Handling of Parameters exceeding String Length: If either the startIndex or endIndex parameter is greater than the length of the string, it is automatically converted to the length of the string. This ensures that the extraction does not extend beyond the string’s boundaries.

Examples

Let’s take a look at some examples to further understand the substring() method:

1
2
3
4
5
6
'This is my car'.substring(5) // Returns 'is my car'
'This is my car'.substring(5, 10) // Returns 'is my'
'This is my car'.substring(5, 200) // Returns 'is my car'
'This is my car'.substring(-6) // Returns 'This is my car'
'This is my car'.substring(-6, 2) // Returns 'Th'
'This is my car'.substring(-6, 200) // Returns 'This is my car'

In the first example, the substring “is my car” is extracted from the original string starting from index 5.

The second example extracts the substring “is my” from the original string, starting from index 5 and ending at index 10 (exclusive).

The third example showcases that the method can handle an endIndex parameter that exceeds the length of the string, resulting in the extraction of the entire remaining string.

The last three examples demonstrate the handling of negative parameters. In each case, the substring is extracted starting from the beginning of the string.

Overall, the substring() method proves to be a valuable tool for extracting specific portions of a string in JavaScript.

tags: [“JavaScript”, “string methods”, “substring method”]