How to select the last two characters of a string
To swiftly get the last two characters of a string, use this quick trick with the slice(-2)
method:
A closer look at slice(-2)
Here's a slice of how JavaScript's slice()
works. In this instance, -2
tells JavaScript to breezily start two steps back from the string's end until it reaches the end. Voilà! You get the last two characters.
The case for short strings
When dealing with strings shorter than two characters, the magnificent slice(-2)
will just return the entire string. It's like asking for two cupcakes when there's only one left - you get what's available.
Null or undefined strings? No worries!
In the wilderness of coding, frequent encounters with null or undefined strings are as common as finding bugs in a garden. The slice()
method is equipped to adeptly handle these.
Advantages of slice()
There's an armory of methods to manipulate strings in JavaScript, like substr()
and substring()
. Among them, slice()
stands tall as the go-to method due to its versatility and simplicity.
Renovating older patterns
Inheritors of legacy codebases, don't fret. Here's how you can trade up from substr()
to slice()
:
Why slice trumps substr
The slice()
method surpasses substr()
not just in versatility, it reflects the consistency of behaviour shared by arrays and strings. It's the way to go for clarity and simplicity!
Handling diverse scenarios
Among its repertoire of tricks, slice()
can adapt to a gamut of situations, coming out unscathed:
Empty strings
An empty string? More like an invisible cloak! But slice()
ain't fooled!
Shorter strings
Less than two characters in a string and slice()
will smartly return what's available. No errors, no fuss!
Large negative indices
Supplying larger negative index to slice()
gives out the whole string. Now, that's generosity!
Was this article helpful?