JavaScript substr()Method
Examples
Extract the specified number of characters:
var n=str.substr(2,3)
nOutput:
Try it Yourself »
Definition and Usage
The substr() method can extract from the string, starting from thestartindex, the specified number of characters.
Tip:The parameters of substr() specify the start position and length of the substring, so it can be used instead of substring() and slice().
In IE 4, the value of the parameter start is invalid. In this bug, start specifies the position of the 0th character. In later versions, this bug has been fixed.
ECMAScript has not standardized this method, so its use is deprecated.
Note:The substr() method does not change the original string.
Browser Support
![]()
![]()
![]()
![]()
![]()
All major browsers support the substr() method
Syntax
Parameter Values
| Parameter | Description |
|---|---|
| start | Required. The starting index of the substring to extract. Must be a numeric value. If it is a negative number, then this parameter declares the position counted from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on. |
| length | Optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, then the substring from the start position of stringObject to the end is returned. |
Return Value
| Type | Description |
|---|---|
| String | A new string containing the extracted part of the text |
Technical Details
| JavaScript Version: | 1.0 |
|---|
More Examples
Examples
In this example, we will use substr() to extract some characters from the second position of the string:
var n=str.substr(2)
nOutput:
Try it Yourself »
Other Extensions
JavaScript String Object