Sometimes, we may want to get the last element of a split string array.
In this article, we’ll look at how to get the last element of a split string array.
Use the Array length Property
We can use the length
property of an array and subtract 1 from it to get the last index of the array.
And we can use the split
method to split a string into an array of strings given a separator string.
For instance, we can write:
const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces[pieces.length - 1]
console.log(last)
We call split
with a regex that matches commas to split the string by the commas.
Then we get the last element in the pieces
split string array with index pieces.length — 1
.
Therefore, last
is 'today?'
.
Use the Array.prototype.pop Method
The array instance’s pop
method removes the last element of an array in place and returns the removed element.
Therefore, we can use it to get the last item of the split string array.
For example, we can write:
const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces.pop()
console.log(last)
And we get the same result as before for last
.
Use the Array.prototype.slice Method
The array instance’s slice
method lets us get a part of an array given the start and end index.
To get the last element of the array, we can pass in index -1 as the start index to return an array that has the last element of the array.
We don’t need the end index since the default value for the end index is the last index of the array.
Therefore, we can write:
const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces.slice(-1)[0]
console.log(last)
We use [0]
to get the first element of the array returned by slice
.
And so we get the same value for last
as before.
Conclusion
We can use various array methods to get the last string in the split string array with JavaScript.