JavaScript substr()
The Javascript substr()
method is used for extracting a portion of a string, starting from the specified index position, and returns a new sub-string. It takes two arguments:
- The starting index position to begin extraction. The index is zero-based.
- The length of the sub-string to be extracted. If this parameter is not specified, the method extracts all the characters from the starting index position till the end of the string.
Syntax
string.substr(start, length)
string
: The original string.start
: The position in the string to start extraction (required).length
: The number of characters to be extracted (optional).
Example
let str = "JavaScript substr() method";
console.log(str.substr(0, 10)); // "JavaScript"
console.log(str.substr(11)); // "substr() method"
console.log(str.substr(1)); // "avaScript substr() method"
Output
"JavaScript"
"substr() method"
"avaScript substr() method"