JavaScript String slice()
Method
Example
Extract a fragment of a string:
var str = "Hello world!";
var n = str.slice(1, 5);
n Output result:
ello
Definition and Usage
The slice(start, end)
method extracts a part of a string and returns the extracted part in a new string.
Use the start
(inclusive) and end
(exclusive) parameters to specify the part of the string to extract.
The start
parameter's first character position is 0, the second character position is 1, and so on. If it is negative, it indicates the number of characters from the end of the string. slice(-2)
extracts the second-to-last element to the last element (including the last element).
The end
parameter, if negative, -1 indicates the position of the last character, -2 indicates the second-to-last character, and so on.
Browser Support
All major browsers support the slice()
method.
Syntax
Parameter Values
Parameter | Description |
---|---|
start | Required. The starting index of the substring to be extracted. The first character position is 0. If negative, it starts from the end of the string. |
end | Optional. The index immediately after the end of the substring to be extracted. If not specified, the substring includes characters from start to the end of the original string. If negative, it specifies the position from the end of the string. slice(-2) extracts the second-to-last element to the last element (including the last element). |
Return Value
Type | Description |
---|---|
String | The extracted string |
Technical Details
| JavaScript Version: | 1.0 | | --- | --- |
More Examples
Example
Extract the entire string:
var str = "Hello world!";
var n = str.slice(0);
Output result:
Hello world!
Example
Extract a substring starting from the 3rd position:
var str = "Hello world!";
var n = str.slice(3);
Output result:
lo world!
Example
Extract a substring from the 3rd position to the 8th position:
var str = "Hello world!";
var n = str.slice(3, 8);
Output result:
lo wo
Example
Extract only the first character:
var str = "Hello world!";
var n = str.slice(0, 1);
Output result:
H
Example
Extract the last character and the last two characters:
var str = "Hello world!";
var n = str.slice(-1);
var n2 = str.slice(-2);
Output result:
!
d!