JavaScript String substr() Method
The substr()
method in JavaScript extracts a portion of a string, starting from a specified index position and extending for a given number of characters.
This method was traditionally used to extract a part of a string, however, the method is now considered outdated, and the substring() or slice() methods are recommended as alternatives.
Syntax:
str.substr(start, length)
Parameters:
- start: The index where the extraction begins.
- length (optional): The number of characters to extract. If omitted, it extracts the rest of the string from the start index.
Return value:
Returns a string that is part of the given string. If the length is 0 or a negative value then it returns an empty string. If we want to extract the string from the end then use a negative start position.
Example 1: Extract Substring using substr()
This code demonstrates the usage of the substr() method in JavaScript. It extracts a substring from the original string starting from the specified index (5 in this case) till the end. The extracted substring is then printed.
// JavaScript to illustrate substr() method
function func() {
// Original string
let str = 'It is a great day.';
let sub_str = str.substr(5);
console.log(sub_str);
}
func();
Output
a great day.
Example 2: Negative Length in substr() Method
This code demonstrates an attempt to use a negative length parameter in the substr() method, which is invalid. JavaScript substr() method expects a positive length value, resulting in an empty string when provided with a negative value.
// JavaScript to illustrate substr() method
function func() {
// Original string
let str = 'It is a great day.';
let sub_str = str.substr(5, -7);
console.log(sub_str);
}
func();
Output
Example 3: Extracting Substring from End Using substr()
This code snippet utilizes the substr() method to extract a substring from the end of the original string ‘It is a great day.’. The negative index -7 indicates starting from the 7th character from the end, and 6 characters are extracted.
// JavaScript to illustrate substr() method
function func() {
// Original string
let str = 'It is a great day.';
let sub_str = str.substr(-7, 6);
console.log(sub_str);
}
func();
Output
at day
Now to use modern methods like substring() or slice() you can follow these articles.
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.