Getting the last element of a split string array
There's a one-liner for everything. :)
var output = input.split(/[, ]+/).pop();
const str = "hello,how,are,you,today?"
const pieces = str.split(/[\s,]+/)
const last = pieces[pieces.length - 1]
console.log({last})
At this point, pieces
is an array and pieces.length
contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]
. If there are no commas or spaces it will simply output the string as it was given.
alert(pieces[pieces.length-1]); // alerts "today?"
var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three
Best one ever and my favorite using split
and slice
const str = "hello, how are you today?"
const last = str.split(' ').slice(-1)[0]
console.log({last})
And another one is using split
then pop
the last one.
const str = "hello, how are you today?"
const last = str.split(' ').pop()
console.log({last})