Getting the last element of a split string array

Viewed 373306

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?

11 Answers

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

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})

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

There are multiple ways to get last elements

let input='one,two,three,four';

let output1 = input.split(',').pop();
console.log('output1 =',output1);

let split = input.split(',');
let output2 = split[split.length-1];
console.log('output2=',output2);

let output3 = input.split(',').reverse()[0];
console.log('output3=',output3);

let output4 = input.split(',').slice(-1)[0];
console.log('output4=',output4);

This way is easy to understand and very short.

const output = input.split(',').pop().split(' ').pop();

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

const str = "how,are you doing, today?";
const last = str.split(/[\s,]+/).at(-1);
console.log({last});

Link to documentation: Array.prototype.at()

Related