Extracting parts of a string, by giving beginning at the character at the specified position : substr()

Java Script @ Freshers.in

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. It’s important to note that the substr() method does not change the original string.

Syntax: Here is the basic syntax of the substr() method:

string.substr(start, length)
  • start: The position where to start the extraction. First character is at index 0. If start is negative, substr() uses it as a character index from the end of the string.
  • length: Optional. The number of characters to extract. If omitted, substr() extracts characters to the end of the string.

Examples and Execution: The following examples illustrate the substr() method’s usage. You can run these examples in any JavaScript environment, such as a web browser console or Node.js.

Basic usage:

let str = "Hello, World!";
let newStr = str.substr(7, 5);
console.log(newStr); // Outputs: "World"
Negative start:
let str = "JavaScript";
let newStr = str.substr(-6, 4);
console.log(newStr); // Outputs: "Scri"
Without length parameter
let originalStr = "JavaScript is amazing!";
let newStr = originalStr.substr(4);
console.log(newStr); // Outputs: "Script is amazing!"
Length exceeding string’s length
let str = "Hello";
let newStr = str.substr(1, 10);
console.log(newStr); // Outputs: "ello" (extracts till the end)
Function to extract substring:
function extractSubString(originalString, start, length) {
    return originalString.substr(start, length);
}

let myString = "The quick brown fox jumps over the lazy dog";
let mySubString = extractSubString(myString, 16, 3);
console.log(mySubString); // Outputs: "fox"

The extractSubString function is a practical application that utilizes the substr() method to extract a sequence of characters from a larger string. This is useful in various scenarios such as parsing responses from APIs, formatting strings for output, and more.

Author: user