Select a substring
Extracting a known range from text
JavaScript · Function
String.prototype.slice() returns a selected section of a string as a new string. The start is inclusive, the end is exclusive, and the original string remains unchanged.
Call slice() on a string with a starting index and, optionally, an exclusive ending index. Negative indexes count backward from the end; the method returns a new string and does not change the original.
slice(indexStart)
slice(indexStart, indexEnd)| Name | Type | Description |
|---|---|---|
indexStart | integer | The zero-based index of the first character included in the result. Negative values count backward from the string's end; omitted or nonnumeric values act as 0. |
indexEnd | integer | Optional zero-based index of the first character excluded from the result. Negative values count backward from the string's end; omitted or sufficiently large values select through the end. |
A new string containing the extracted section of the string.
indexStart identifies the first included character.indexEnd is exclusive rather than inclusive.const text = "JavaScript";
const part = text.slice(4, 10);
console.log(part); // "Script"Extracts characters at indexes 4 through 9 and leaves the original string unchanged.
Extracting a known range from text
Removing a prefix or suffix for display
Reading the final characters of a value
String.prototype.slice() returns the selected portion as a new string. The start is included, while the end is excluded, and the original string is not modified.
Follow-up: What does slice(2, -1) do? It starts at index 2 and stops before the final character after normalizing the negative end index.
The first parameter is the index of the first character to include. The optional second parameter is the index of the first character to exclude; omitting it extracts through the end.
Follow-up: What happens when the end index is less than or equal to the start index? The method returns an empty string.
A negative index is measured from the end of the string. If the start is negative, the effective start is the string length plus that value, with a lower bound of zero.
Follow-up: What happens when the start is greater than or equal to the string length? The result is an empty string.
String.prototype.substring()String.prototype.substr()Array.prototype.slice()