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. - Pass the separator as a parameter.
- Call the
pop()
method on the array. - The
pop()
method will return the last element in the split string array.
Separators are also known as delimiters.
Example –
const theString = 'one,two,three';
const result = theString.split(',').pop();
console.log(result);
split()
and pop()
method.Here’s what the above code doing:
- We have a string with three words separated by commas.
- We call the
split()
method on the string, which returns an array of the words. - We call the
pop()
method on the array, which returns the last word. - We log the result to the console.
The split()
method is called on the string ‘one,two,three’ and the .pop()
method is called on the array that split()
returns.
If you need to use the split()
method with multiple separators, use a regular expression as an argument for the method.
Example –
const theString = 'one two_three';
console.log(theString.split(/[s_]+/));
Here’s what the above code is doing:
- The split() method takes a regular expression as an argument.
- The regular expression is /[s_]+/.
- The split() method returns an array of strings.
- The array of strings is [“one”, “two”, “three”].
/[s_]+/
– matches one or more whitespace or underscore characters.
The part of the text between square brackets [] is called a character class. This class of characters matches one of the characters between the brackets.
The plus sign (+) indicates that the preceding element (space or underscore) should be matched one or more times.
The split()
method is used to split a string into an array of substrings, and returns the new array.
Note: The split()
method does not change the original string.
Tip: If an empty string (“”) is used as the separator, the string is split between each character.
If you ever need help understanding a regular expression, refer to this regex cheatsheet from MDN.
The last step is to use the Array.pop()
method to remove and return the last element from the array.
Example –
console.log(['one', 'two', 'three'].pop());
Here’s what the above pop is doing:
- The
pop()
method is called on the array [‘one’, ‘two’, ‘three’]. - The last element of the array is removed.
- The element that was removed, ‘three’, is returned.
The pop() method changes the contents of an array, but it does not matter in this case because we are using a temporary array.