Slice the first 5 positions:
let text = "Hello world!";
let result = text.slice(0, 5);
Try it Yourself »
From position 3 to the end:
let result = text.slice(3);
Try it Yourself »
More examples below.
The slice()
method extracts a part of a string.
The slice()
method returns the extracted part in a new string.
The slice()
method does not change the original string.
The start and end parameters specifies the part of the string to extract.
The first position is 0, the second is 1, ...
A negative number selects from the end of the string.
string.slice(
start,
end)
Parameter | Description |
start | Required. The start position. (First character is 0). |
end | Optional. The end position (up to, but not including). Default is string length. |
Type | Description |
A string | The extracted part of the string. |
From position 3 to 8:
let result = text.slice(3, 8);
Try it Yourself »
Only the first character:
let result = text.slice(0, 1);
Try it Yourself »
Only the last character:
let result = text.slice(-1);
Try it Yourself »
The whole string:
let result = text.slice(0);
Try it Yourself »
slice()
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!