The String slice() method
By Flavio Copes
Learn how the JavaScript slice() method returns a new portion of a string between a begin and end position, and how negative indexes count back from the end.
slice() returns a new string containing the part of the original string between a begin and an end position. The original string is not mutated.
The end position is optional. If you omit it, the slice runs to the end of the string:
'This is my car'.slice(5) //'is my car'
'This is my car'.slice(5, 10) //'is my'
Notice that the character at the end index is not included. slice(5, 10) grabs the characters at index 5, 6, 7, 8 and 9.
You reach for slice() whenever you need a piece of a string and you know the positions: trimming a prefix, cutting a string to a maximum length, extracting a fragment.
Using negative indexes
Negative values count back from the end of the string. This is the feature that makes slice() handy: you can grab the tail of a string without calculating its length first.
'This is my car'.slice(-6) //'my car'
'This is my car'.slice(-6, -4) //'my'
A realistic example, extracting a file extension:
const filename = 'report.pdf'
filename.slice(-3) //'pdf'
You can also mix positive and negative indexes, as long as the start position comes before the end position:
'This is my car'.slice(8, -4) //'my'
What happens with out-of-range values?
If begin points at or after end, you get an empty string. No error, no swapping:
'This is my car'.slice(10, 5) //''
This is the pitfall to watch for. An empty string in the output usually means your two indexes are in the wrong order, or a negative index resolved to a position after the end one. Log both values and check which one is off.
If end goes past the string length, slice() stops at the end of the string without complaining:
'This is my car'.slice(11, 100) //'car'
How is it different from substring()?
substring() looks identical at first, but it behaves differently on tricky input. It swaps the arguments when begin is greater than end, and it treats negative values as 0:
'This is my car'.substring(10, 5) //'is my'
'This is my car'.substring(-6) //'This is my car'
I prefer slice(): the behavior is predictable, and negative indexes are genuinely useful.