Last updated: Jul 25, 2022
Check out my new book
To split a string and get the last element of the array, call the
method on the string, passing it the separator as a parameter, and then call the
pop() method on the array, e.g.
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(','))
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.
+ means match the preceding item (space or underscore) one or more
+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.
pop() method removes and returns the last array element.
// 👇️ "three" console.log(['one', 'two', 'three'].pop());
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.