How to Create Array from a Comma-Separated String in JavaScript
Sometimes you have a comma-separated string and you want to convert it to an array.
A good example is if you're reading a CSV file and you want to retrieve the data as an array.
In this post, we'll learn how to create an array from a comma-separated string in JavaScript.
How to create an array from a comma-separated string in JavaScript
To start, let's define an example comma-separated string:
JAVASCRIPTconst string = "apple,banana,orange";
Now, we can use the built-in split
method and pass it a separator, in this case, a comma, and it will take our string and turn it into an array.
JAVASCRIPTconst string = "apple,banana,orange";
const array = string.split(",");
console.log(array);
BASH[ 'apple', 'banana', 'orange' ]
That's all there is to it.
In case you want to limit how many times the separator is used, you can pass an optional second argument to the split
method.
Let's say you only want the first two elements:
JAVASCRIPTconst string = "apple,banana,orange";
const array = string.split(",", 2);
console.log(array);
BASH[ 'apple', 'banana' ]
Alternatively, if you pass the method a blank string as the separator, it will simply split the string into individual characters.
JAVASCRIPTconst string = "apple,banana,orange";
const array = string.split("");
console.log(array);
BASH[ 'a', 'p', 'p', 'l', 'e', ',', 'b', 'a', 'n', 'a', 'n', 'a', ',', 'o', 'r', 'a', 'n', 'g', 'e' ]
Conclusion
In this post, we looked at the different ways to create an array from a comma-separated string in JavaScript.
Simply use the split
method and pass it a separator and the return value will be an array.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Getting Started with React
- Setting Up a Local Web Server using Node.js