The substring() method in JavaScript extracts characters from a string, between two specified indices, and returns the new sub string. This method returns the part of the string between the start and end indexes, or to the end of the string.
Syntax:
The basic syntax of the substring() method is as follows:
string.substring(indexStart, indexEnd)
- indexStart: The zero-based index at which to start extraction.
- indexEnd: Optional. The zero-based index before which to end extraction. The character at this index will not be included. If omitted, substring() extracts characters to the end of the string.
Unlike slice(), the substring() method cannot accept negative indices. If either argument is less than 0 or is NaN, it is treated as if it were 0.
Examples
Here are some practical examples of the substring() method. You can copy and execute these examples in any JavaScript environment, like browser developer tools, online editors, or Node.js.
Basic usage:
let str = "Hello, World!";
let newStr = str.substring(7);
console.log(newStr); // Outputs: "World!"
let str = "JavaScript";
let newStr = str.substring(4, 10);
console.log(newStr); // Outputs: "Script"
let originalStr = "Unchanged";
let newStr = originalStr.substring(2, 7);
console.log(newStr); // Outputs: "chang"
console.log(originalStr); // Outputs: "Unchanged" (original string is not modified)
let str = "Hello";
let newStr = str.substring(1, 10);
console.log(newStr); // Outputs: "ello" (goes up to the string's length only)
function extractSubString(originalString, start, end) {
return originalString.substring(start, end);
}
let myString = "I love JavaScript!";
let mySubString = extractSubString(myString, 7, 17);
console.log(mySubString); // Outputs: "JavaScript"