JavaScript String slice()
Examples
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.
Definition and Usage
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.
Syntax
string.slice(start, end)
Parameters
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. |
Return Value
Type | Description |
A string | The extracted part of the string. |
More Examples
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 »
Browser Support
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 |