JavaScript String substr()
Examples
Extract a substring from text:
let text = "Hello world!";
let result = text.substr(1, 4);
Try it Yourself »
Start at position 2:
let result = text.substr(2);
Try it Yourself »
More examples below.
Description
The substr()
method extracts a part of a string.
The substr()
method begins at a specified position, and returns a specified number of characters.
The substr()
method does not change the original string.
To extract characters from the end of the string, use a negative start position.
Syntax
string.substr(start, length)
Parameters
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
Return Value
Type | Description |
A string | A string containing the extracted part. If length is 0 or negative, an empty string is returned. |
More Examples
Only the first:
let result = text.substr(0, 1);
Try it Yourself »
Only the last:
let result = text.substr(text.length-1, 1);
Try it Yourself »
The last 6:
let result = text.substr(-6, 6);
Try it Yourself »
Browser Support
substr()
is an ECMAScript1 (JavaScriopt 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |