Extract a substring from text:
let text = "Hello world!";
let result = text.substring(1, 4);
Try it Yourself »
Start from position 2:
let result = text.substring(2);
Try it Yourself »
More examples below.
The substring()
method extracts characters, between two indices (positions), from a string, and returns the substring.
The substring()
method extracts characters from start to end (exclusive).
The substring()
method does not change the original string.
If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
Start or end values less than 0, are treated as 0.
string.substring(
start, end)
Parameter | Description |
start | Required. Start position. First character is at index 0. |
end | Optional. End position (up to, but not including). If omitted: the rest of the string. |
Type | Description |
A string | A string containing the extracted characters. |
If start is greater than end, parameters are swapped:
let result = text.substring(4, 1);
Try it Yourself »
If "start" is less than 0, it will start from index 0:
let result = text.substring(-3);
Try it Yourself »
Only the first:
let result = text.substring(0, 1);
Try it Yourself »
Only the last:
let result = text.substring(text.length - 1);
Try it Yourself »
substring()
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!