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?"