The substr() method in JavaScript is used to extract a portion of a string, starting from a specified index to a specified length.
Syntax: string.substr(startIndex, length)
- string: The string from which you want to extract the substring.
- startIndex: The index where the extraction will begin. If negative, it starts from the end of the string.
- length: The number of characters to extract. If omitted or greater than the remaining length of the string, it extracts until the end of the string.
Example:
let str = "Hello, World!";
let subString = str.substr(7, 5);
console.log(subString); // Output: World
Explanation:
- We have a string str containing the text "Hello, World!".
- We use substr(7, 5) to extract a substring starting from index 7 (inclusive) with a length of 5 characters.
- The extracted substring is "World", which is then stored in the variable subString and logged to the console.