JavaScript Reference ยท String
String.prototype.slice()
Reference for JavaScript String.prototype.slice(): extract a section of a string by start and end index, with negative indexes, and compare it to substring().
The slice() method returns a section of a string as a new string. You give it a start index and an optional end index. The character at the start is included; the character at the end is not.
Negative indexes count back from the end of the string, which makes slice(-3) a neat way to take the last three characters. If you can pick only one method for extracting text, slice() is the most predictable, and it matches Array.prototype.slice().
"JavaScript".slice(0, 4); // "Java"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.slice(indexStart) string.slice(indexStart, indexEnd)
| Name | Description |
|---|---|
indexStart |
Where to begin (included). A negative value counts from the end (length + indexStart). If it is below -length, it becomes 0. Missing or undefined means 0. |
indexEnd |
Where to stop (not included). A negative value counts from the end. If omitted or larger than the length, the slice runs to the end of the string. |
Return value: a new string containing the extracted part.
Exceptions: none.
Usage notes
- The end is exclusive, so
slice(a, b)has lengthb - awhen both are inside the string. - If the start is at or after the end, the result is an empty string. Unlike
substring(),slice()does not swap the arguments. - Negative indexes are supported, which is the main difference from
substring(), where negative values become0. - Values are converted to integers: fractions are truncated, and
NaNbecomes0. - Out-of-range values never throw. Indexes beyond the string are clamped.
substr()is deprecated in practice (it takes a start and a length). Preferslice().- Code units, not characters. Indexes count UTF-16 code units, so slicing between the two halves of an emoji produces broken text. Use
Array.from(str)or the spread operator to work with code points. - Strings are immutable, so the original is never changed; you always get a copy.
Browser support
String.prototype.slice() is supported in every browser.