Getting the last element of a split string array
var str = "hello,how,are,you,today?";var pieces = str.split(/[\s,]+/);
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