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:
- Handling of Negative Parameters: If either the
startIndex
orendIndex
parameter is negative, it is automatically converted to 0. This means that the substring extraction will start from the beginning of the string. - Handling of Parameters exceeding String Length: If either the
startIndex
orendIndex
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 | 'This is my car'.substring(5) // Returns '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”]