How to Split a String and get Last Array Element in JavaScript
When you are working with strings with a repeated pattern like a comma-separated list, it is common to split the string into an array of elements.
After that, you might need to get the last element in the array.
In this post, we'll learn how to split a string into an array and get the last element in the array in JavaScript.
Split a string into an array
The easiest way to split a string into an array is to use the split()
method.
This method takes a string as an argument and returns an array of elements.
First, let's define the string we want to split.
JAVASCRIPTconst string = "a,b,c,d,e";
Now let's split this by the comma character.
JAVASCRIPTconst string = "a,b,c,d,e";
const array = string.split(",");
As mentioned before, the split()
method returns an array of elements.
JAVASCRIPTconst string = "a,b,c,d,e";
const array = string.split(",");
console.log(array);
// ["a", "b", "c", "d", "e"]
Get the last element in the array
Now that we have an array of elements, we can get the last element in the array.
The easiest way to get the last element in the array is to use the pop()
method.
Let's use the pop()
method to get the last element in the array.
JAVASCRIPTconst string = "a,b,c,d,e";
const array = string.split(",");
const lastElement = array.pop();
console.log(lastElement);
// e
Conclusion
In this post, we learned how to split a string into an array and get the last element in the array in JavaScript.
Simply use the split()
method to split a string into an array and then use the pop()
method to get the last element in the array.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor