Skip to content
Advertisement

Getting the last element of a split string array

I need to get the last element of a split array with multiple separators. The separators are commas and space. If there are no separators it should return the original string.

If the string is “how,are you doing, today?” it should return “today?”

If the input were “hello” the output should be “hello”.

How can I do this in JavaScript?

Advertisement

Answer

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