Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last element of a split string array

People also ask

How do you split the last element in Python?

Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

What removes the last element of an array and return it?

To remove the last element from an array, call the pop() method on the array, e.g. arr. pop() . The pop method removes the last element from the array and returns it.


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

var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three

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

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.