String substr()
In JavaScript, String.substr()
method is used to find the substring of a string which is defined by a specific start index, and an optional length.
Syntax
str.substr(start) #if no length, then till the end
str.substr(start, length)
where
str
is a string.start
is a number.length
is a number.
substr()
method finds the substring of given length from the given start.
Examples
1. In the following program, we find the substring of a string value in name
, where the substring is defined by a specific start index.
let name = 'abcdefghijklmn';
let output = name.substr(6);
console.log(output);
2. substr(start) with start as negative number. If we give a negative value for index, then the index is considered from end towards start.
let name = 'abcdefghijklmn';
let output = name.substr(-6);
console.log(output);
3. In the following program, we find the substring of a string value in name
, where the substring is defined by a specific start index in the string, and for a specific length.
let name = 'abcdefghijklmn';
let output = name.substr(6, 5);
console.log(output);