JavaScript substr() Method
Example
Extract a specified number of characters:
var str="Hello world!";
var n=str.substr(2,3)
n Output result:
llo
Try it »
Definition and Usage
The substr() method extracts a specified number of characters from a string starting at the *start* index.
Tip: The parameters of substr() specify the start position and length of the substring, so it can be used as a substitute for 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 discouraged.
Note: The substr() method does not change the source string.
Browser support





All major browsers support the substr() method.
Syntax
string
.substr(
start
,
length
)
Parameter value
| Parameters | Description |
|---|---|
| start | Required. The starting index of the substring to extract. Must be a numeric value. If negative, this parameter specifies a 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, the substring from the beginning 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
Example
In this example, we will use substr() to extract some characters from the second position of the string:
var str="Hello world!";
var n=str.substr(2)
n Output result:
llo world!
Try it »
JavaScript String object