Split a String and get the Last Array Element in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 17 20212 min read

banner

Photo by Lison Zhao

Split a String and get the Last Array Element #

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str.split(',').pop(). The pop() method will return the last element from the split string array.

index.js
const str = 'one,two,three'; const result = str.split(',').pop(); console.log(result); // ๐Ÿ‘‰๏ธ three

The only parameter we passed to the String.split method is the separator.

In the example, we split the string on each comma.

index.js
const str = 'one,two,three'; // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log(str.split(','))

If you need to use the split() method with multiple separators, you can pass the method a regular expression instead.

The following example splits on every space or underscore.

index.js
const str = 'one two_three'; // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log(str.split(/[\s_]+/));

The square brackets part is called a character class and matches either one of the characters between the brackets.

The plus + means match the preceding item (space or underscore) one or more times.

We use the plus, because we want to match all occurrences of the characters and not just the first occurrence.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

The last step is to use the Array.pop method to get the last element from the array.

The pop() method removes and returns the last element from an array.

index.js
// ๐Ÿ‘‡๏ธ "three" console.log(['one', 'two', 'three'].pop());

The pop() method changes the contents of the array in place, however it doesn't really matter in this case, because we're using a throwaway array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee