269

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?

JJJ
  • 32,902
  • 20
  • 89
  • 102

11 Answers11

1013

There's a one-liner for everything. :)

var output = input.split(/[, ]+/).pop();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 8
    Issue here is that pop() also *removes* that element from the array, thereby changing it. – slashwhatever Apr 10 '12 at 15:40
  • 81
    @Jangla: That's not a problem, as the array is created by the `split` call, it's not kept anyway. The original string is not changed by popping the item from the array. – Guffa Apr 10 '12 at 15:58
  • 1
    brilliant, all in one go, no need for intermediary var to setup the array...nice – virtualeyes Sep 23 '12 at 08:26
  • @Guffa Do you know how can I get last two elements of split? – Vitor Oct 16 '15 at 21:52
  • 2
    @VitorGuerreiro: Yes, you can use the `slice` method: `var output = input.split(/[, ]+/).slice(-2);`. – Guffa Oct 17 '15 at 08:39
  • What's the purpose of the '+' ? – Mario Levrero Dec 15 '15 at 12:51
  • 2
    @MarioLevrero: That's a quantifier that means the same as the quantifier `{1,}`, i.e. `[, ]+` matches one or more of the characters in the set (comma and space). It's useful when you want all the words from the string, but when you only want the last word it doesn't make any functional difference, it only reduces the overhead as there will be fewer strings in the array. – Guffa Dec 15 '15 at 15:27
158

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?"
Teocci
  • 7,189
  • 1
  • 50
  • 48
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
107
var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three
Pavel
  • 5,374
  • 4
  • 30
  • 55
mohawke
  • 1,107
  • 1
  • 7
  • 2
  • 10
    I don't think pop() takes arguments. – Grace Huang Jun 12 '12 at 21:22
  • @GraceShao: yep. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop – aymericbeaumet Jan 23 '15 at 16:59
  • 6
    But, generically speaking `.split(',').pop()` works for last element on comma separated string. Just sayin' cuz I was misled by Guffa's awesome answer, I just disregarded it because didn't need a regex and thought the trick was there! :P – cregox May 29 '15 at 08:01
41

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})
Teocci
  • 7,189
  • 1
  • 50
  • 48
jithil
  • 1,098
  • 11
  • 11
34

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()
Smile4ever
  • 3,491
  • 2
  • 26
  • 34
  • 4
    The `.pop()` method is the best answer I've seen so far. That's why it was created! – Nicholas Porter Feb 20 '20 at 22:43
  • 1
    I'd strongly advise against reverse() because reversing will be expensive on large arrays. If you don't care about mutation, simply use pop(), otherwise slice(-1)[0]. – wortwart Apr 07 '20 at 14:45
  • its increasing the time complexity since you have an extra loop to reverse the array. – jithil May 10 '21 at 07:39
4

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);
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
4

This way is easy to understand and very short.

const output = input.split(',').pop().split(' ').pop();
David Vicente
  • 3,091
  • 1
  • 17
  • 27
4

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

Denis Bubnov
  • 2,619
  • 5
  • 30
  • 54
3

And if you don't want to construct an array ...

var str = "how,are you doing, today?";
var res = str.replace(/(.*)([, ])([^, ]*$)/,"$3");

The breakdown in english is:

/(anything)(any separator once)(anything that isn't a separator 0 or more times)/

The replace just says replace the entire string with the stuff after the last separator.

So you can see how this can be applied generally. Note the original string is not modified.

Tony
  • 18,776
  • 31
  • 129
  • 193
0
var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";
Bart
  • 9,925
  • 7
  • 47
  • 64
0

You can access the array index directly:

var csv = 'zero,one,two,three'; csv.split(',')[0]; //result: zero csv.split(',')[3]; //result: three

tnong
  • 19
  • 2