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.
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.
string.substr(
start,
length)
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 |
Type | Description |
A string | A string containing the extracted part. If length is 0 or negative, an empty string is returned. |
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 »
substr()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!