JavaScript String slice()
Examples
Slice the first 5 positions:
let result = text.slice(0, 5);
From position 3 to the end:
More examples below.
Description
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
Parameters
The start position.
(First character is 0).
The end position (up to, but not including).
Default is string length.
Return Value
More Examples
From position 3 to 8:
Only the first character:
Only the last character:
The whole string:
Browser Support
slice()
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |