Getting the last element of a split string array
Want the last element of an array derived from a split string? Here's fast food for your code using split()
and pop()
:
No need to loop. pop()
simply serves the last item post-split. Handling different separators, such as spaces? Try this recipe with a regular expression:
This technique doesn't let trailing separators rob the toast of your bread! 🍞
Nitty-gritty methods
When your string enjoys costume parties
What happens when your delimiters come in a cocktail of forms? You can still split with multiple separators like commas or spaces using:
Now the party (/[, ]+/) doesn't stop at commas and spaces!
Safe wisdom in a crowd
If your crowd (the string) may not have any separators at all, this function won't leave you alone:
Trimming that stylish beard
Whitespace can sometimes be your string's beard. Time to give it a trim before splitting:
Road less travelled
Look Ma, no modifications!
You wish to preserve the array while accessing the last element because, who likes spoilers?
Overturned cart- not on this road
You might see reverse()[0]
for getting the last element, but best to dump it in the bin 🗑️ because it:
- Upends the original array like an overturned cart.
- Is a lousy performer in front of large crowds (arrays).
Checking under the hood
While testing your function with various strings, console.log()
is your friendly mechanic:
Use alert(thingToAlert)
to flash alerts to the user in a UI context.
Was this article helpful?