Extracting characters from a string, between two specified indices using JavaScript : substring()

Java Script @ Freshers.in

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!"
Substring with both indices
let str = "JavaScript";
let newStr = str.substring(4, 10);
console.log(newStr); // Outputs: "Script"
No modifications on original string:
let originalStr = "Unchanged";
let newStr = originalStr.substring(2, 7);
console.log(newStr); // Outputs: "chang"
console.log(originalStr); // Outputs: "Unchanged" (original string is not modified)
Indices greater than the string’s length:
let str = "Hello";
let newStr = str.substring(1, 10);
console.log(newStr); // Outputs: "ello" (goes up to the string's length only)
Function to extract substring:
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"
We’ve created a reusable function extractSubString demonstrating a practical scenario where you might need to extract a substring from a larger string. This is common in tasks like parsing file names, extracting readable data from code, or even formatting strings in user interfaces.
Author: user