Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
The substring()
method in JavaScript is used to extract a portion of a string and return it as a new string without modifying the original string.
It's similar to the slice() method but with some differences in behavior. Here's a deep dive into the substring()
method in JavaScript:
javascriptstring.substring(start);
string.substring(start, end);
string: The string from which you want to extract a substring.
start: The index at which the extraction begins. If negative, it's treated as 0.
end (optional): The index at which the extraction ends (but doesn't include the character at this index). If omitted, extraction goes up to the end of the string. If negative, it's treated as 0.
javascriptconst text = "Hello, World!";
const subText = text.substring(7, 12);
console.log(subText); // "World"
In this example, the substring()
method extracts characters from index 7 to index 12 (exclusive) from the text string and returns a new string with those characters.
Negative indices are handled differently in the substring()
method. If the start or end index is negative, it's treated as 0:
javascriptconst text = "Hello, World!";
const subText = text.substring(-3, -1);
console.log(subText); // "He"
Here, the start and end indices, which are negative, are treated as 0, resulting in a substring that starts from index 0 and goes up to index 2 (exclusive).
When you omit the end index, the substring()
method continues extracting characters until the end of the string:
javascriptconst text = "Hello, World!";
const subText = text.substring(7);
console.log(subText); // "World!"
The substring()
method starts at index 7 and extracts characters until the end of the text string.
The substring()
method returns a new string containing the extracted characters. It does not modify the original string.
substring()
is a non-mutating method, meaning it doesn't change the original string. It is suitable for working with immutable data structures.
Extracting substrings from a larger string.
Trimming or extracting portions of text.
Creating a copy of a string without modifying the original.
The substring()
method is a versatile tool for working with substrings in JavaScript. It is commonly used in text manipulation, string manipulation, and various other scenarios where you need to extract specific portions of a string.