String.prototype.slice
Returns part of a string.
Available since: ES3
Syntax
str.slice(indexStart, indexEnd)Parameters
| Parameter | Type | Description |
|---|---|---|
| indexStart | number | Position of the first character, counting from zero. A negative value counts from the end of the string. |
| indexEnd | number | Optional. The position to stop before. Defaults to the end of the string. |
Return value
stringA new string with the selected characters.
Examples
The first three characters:
console.log('Programme'.slice(0, 3));Output:
ProNegative values count from the end:
console.log('Programme'.slice(-5));
console.log('Programme'.slice(0, -1));Output:
ramme
ProgrammNotes
The original string is not modified. The character at indexEnd is not included in the result.
See also
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
- String.prototype.split — Splits a string into an array by a separator.
- String.prototype.substring — Returns the part of a string between two positions.
- String.prototype.at — Returns the character at a position; negative indexes are allowed.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.