Split a String and get the Last Array Element in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Check out my new book

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.

const str = 'one,two,three'; const result = str.split(',').pop(); console.log(result); // 👉️ three

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

We split the string on each comma in the example.

const str = 'one,two,three'; // 👇️ ['one', 'two', 'three'] console.log(str.split(','))
If you need to use the split() method with multiple separators, pass a regular expression to the method.

The following example splits on every space or underscore.

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 used the plus + because we consider one or more spaces or underscores next to one another a single match.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN.

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 array element.

// 👇️ "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.

Use the search field on my Home Page to filter through my more than 3,000 articles.