The JavaScript string.slice() method
The slice() method pulls out part of a string and returns it as a new string, from a start index up to (but not including) an end index. "JavaScript".slice(0, 4) gives "Java". It accepts negative indices that count from the end, which is what makes it the most convenient of the substring methods.
Overview
slice() extracts a chunk of a string. Give it a start index and an end index and you get back the characters in between — start included, end excluded. So slice(0, 4) returns the first four characters. Leave off the end and it runs to the finish; leave off both and you get a copy of the whole string.
Its best feature is negative indices: slice(-3) returns the last three characters, and slice(-4, -1) works from the end too. That makes common jobs — grabbing a file extension, trimming the last character — neat one-liners. Strings are immutable, so you always get a new string and the original is untouched.
There are three overlapping methods here, and the confusion is real. slice() handles negatives (use this one). substring() is similar but treats negatives as 0 and swaps its arguments if they're out of order. substr() takes a start and a length and is deprecated. For new code, reach for slice() and you'll rarely need the others.
Syntax
const part = str.slice(start)
const part = str.slice(start, end)
"JavaScript".slice(0, 4) // "Java"
"JavaScript".slice(-6) // "Script"
Parameters
The string.slice() method accepts the following parameters.
| Parameter | Description |
|---|---|
start |
Index to start from (0-based). Negative counts from the end of the string. |
end |
Optional. Index to stop before (not included). Negative counts from the end. Defaults to the string length. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const file = 'report-2026.pdf';
const ext = file.slice(-3); // last 3 chars
const name = file.slice(0, file.indexOf('.'));
document.getElementById('out').textContent =
'name: ' + name + '\n' +
'ext: ' + ext; // name: report-2026 / ext: pdf
</script>
Best practices
- Prefer
slice()oversubstring()and the deprecatedsubstr()— it handles negative indices. - Use negative indices for "from the end" jobs, like
str.slice(-4)for a file extension. - Remember
endis exclusive:slice(0, 3)returns three characters. - Use the return value — strings are immutable, so the original never changes.
Frequently asked questions
What is the difference between slice() and substring()?
slice() supports negative indices (counting from the end), while substring() treats negatives as 0 and swaps the arguments if start > end. slice() is the more predictable choice.How do I get the last few characters of a string?
str.slice(-3) returns the last three characters.Does slice() change the original string?
Should I use substr()?
substr() is deprecated. Use slice() (or substring()) in new code.