JavaScript String slice() method
- Previous Page search()
- Next Page split()
- Go to the Previous Level JavaScript String Reference Manual
Definition and Usage
slice()
The method extracts a part of the string.
slice()
The method returns the extracted part as a new string, without changing the original string.
start and end The parameter specifies the part of the string to be extracted.
The first position is 0, the second is 1, ...
Negative numbers start from the end of the string.
See also:
Instance
Example 1
Cut the first 5 positions:
let text = "Hello world!"; let result = text.slice(0, 5);
Example 2
From position 3 to the end:
let result = text.slice(3);
Example 3
From position 3 to 8:
let result = text.slice(3, 8);
Example 4
Only the first character:
let result = text.slice(0, 1);
Example 5
Only the last character:
let result = text.slice(-1);
Example 6
The entire string:
let result = text.slice(0);
Syntax
string.slice(start, end)
Parameter
Parameter | Description |
---|---|
start |
Required. Starting position. The first character is 0. |
end |
Optional. End position (up to, but not including). Default is the length of the string. |
Return value
Type | Description |
---|---|
string | the part of the string extracted. |
Technical details
Parameter start
This parameter is the starting index of the segment to be extracted. If it is negative, this parameter specifies the position from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second last character, and so on.
Parameter end
This parameter is the index of the end of the next segment to be extracted. start to the end of the original string. If this parameter is negative, it specifies the position from the end of the string.
Return value
a new string. Includes the string string from start (including startto end (excluding end(up to, but not including)
Description
The slice() method returns a string containing string a substring of the string, or return a substring of it. However, this method does not modify string.
methods of String objects slice()
,substring()
and substr()
(not recommended for use) can all return a specified part of the string.slice()
than substring()
be more flexible, as it allows the use of negative numbers as parameters.slice()
with substr()
is different, as it uses two character positions to specify the substring, and substr()
then specify the substring using character position and length.
It should also be noted that,String.slice()
with Array.slice()
similar.
browser support
slice()
is an ECMAScript1 (ES1) feature.
All browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
support | support | support | support | support | support |
- Previous Page search()
- Next Page split()
- Go to the Previous Level JavaScript String Reference Manual