JavaScript String substr() method
- Previous page startsWith()
- Next Page substring()
- Go Up One Level JavaScript String Reference Manual
Definition and usage
substr()
The method extracts a part of the string.
substr()
The method starts from the specified position and returns the specified number of characters.
substr()
The method does not change the original string.
To extract characters from the end of the string, use a negative starting position.
Tip:substr()
method specifies the starting position and length of the substring, it is substring()
method and slice()
A useful alternative to the method, the latter two specify the position of the starting character.
See also:
Instance
Example 1
Extract substrings from the text:
let text = "Hello world!"; let result = text.substr(1, 4);
Example 2
Start from position 2:
let result = text.substr(2);
Example 3
Extract only the first one:
let result = text.substr(0, 1);
Example 4
Extract only the last one:
let result = text.substr(text.length-1, 1);
Example 5
Extract the last six:
let result = text.substr(-5, 5);
Syntax
string.substr(start, length)
Parameter
Parameter | Description |
---|---|
start |
Required. Starting position. The first character is at index 0. If start greater than the length, substr() returns "". If start If negative, substr() counts from the end of the string. |
length |
Optional. The number of characters to extract. If omitted, the rest of the string is extracted. |
Return value
Type | Description |
---|---|
String |
The string containing the extracted part. If the length is 0 or negative, an empty string is returned. |
Browser support
substr() is an ECMAScript1 (ES1) feature.
All browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support | Support |
- Previous page startsWith()
- Next Page substring()
- Go Up One Level JavaScript String Reference Manual