What's the scoop on String.slice vs String.substring?
Anchor your focus here first, 🎯: String.slice()
is friendly with negative indexes making them start from the end, while String.substring()
finds negatives quite unpalatable and converts them to 0. Enter slice
, when end
flips and becomes less than start
, it hands out an empty string; but substring
does you a favor and swaps start
and end
to keep the party going.
Taming the beast: Negative and Out-of-range parameters
Negative parameters: The different tastes
While String.slice(start, end)
and String.substring(start, end)
may look alike, their tastes differ when served negative values. If index goes on a vacation and is out of range, both will call upon the string's length to fill in:
slice
treats a negative start as the tail of the chute, following the end of the string into the abyss. For a negative end index, it's a hop, skip and jump to string's length minus that naughty absolute index.substring
plays safe and treats negative or NaN parameters as 0. If it finds the start index to be larger than stop index, it just flips over the two.
Out-of-range parameters: The common stand
Whether you are a slice
patron or a substring
loyalist, if you want to ncmpress a segment right to the end of the string without specifying an end index, you're in luck. Both roll out the red carpet and default to slicing till the string's end.
A substr
workaround
With substr()
being shown the exit (Yes, it's deprecated), slice
and substring
are here to stay. Here's a replacement for substr
using substring
:
Being mindful of your audience's browser makes quite a difference. slice
seemingly is quite a modernist with negative parameters, trailing reluctantly only on IE8 and lower.
Taking charge: The finer approaches
Embracing negatives
Where you require the tail end, slice
stands as your best bet:
Swapping salvation
slice
would give you empty-handed if start
is greater than end
. Alternate route, substring
, flips them to still offer some bounty:
The out-of-range savior
Incase you overshoot, both slice
and substring
won't leave you hanging. They rope in the string's length if an index goes too far:
Picking the right tool
Your selection between slice
and substring
should hinge on the context. slice
fares well with endings and substrings, especially from the rear. substring
may hold ground where your parameters are more balanced and predictable.
Was this article helpful?