Convert a Comma Separated String to Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert a Comma Separated String to Array #

Use the String.split() method to convert a comma separated string to an array, e.g. const arr = str.split(','). The split() method will split the string on each occurrence of a comma and will return an array containing the results.

index.js
const str = 'apple,banana,corn,dates'; const arr = str.split(','); // 👇️ ['apple', 'banana', 'corn', 'dates'] console.log(arr);
If your string has spaces after the commas, scroll down to the next code snippet.

We used the String.split method to split a string into an array.

The only argument we passed to the method is a separator. The separator marks where each split should occur.

The split method returns an array containing the split strings.

However, the words in your string might by separated by a comma and a space:

index.js
const str = 'apple, banana, corn, dates'; // 👇️ ['apple', ' banana', ' corn', ' dates'] console.log(str.split(','))

In this scenario, we have to update the parameter we pass to the split() method:

index.js
const str = 'apple, banana, corn, dates'; const arr = str.split(', '); // 👇️ ['apple', 'banana', 'corn', 'dates'] console.log(arr);
We passed a comma and a space as the separator to the split method. Now the strings in the array do not have leading spaces.

If the split() method is called on an empty string, it returns an array containing an empty string, and not an empty array.

index.js
const str = ''; const arr = str.split(','); console.log(arr); // 👉️ ['']

If you want to get an empty array when the string is empty, you can chain a filter() call after the split method.

index.js
const str = ''; const arr = str.split(',').filter(element => element !== ''); console.log(arr); // 👉️ []
The function we passed to the filter() method gets called with each element in the array.

The filter method returns an array containing only the elements that satisfy the condition in the function.

We don't want the array to contain empty strings, so we only return true if the element is not equal to an empty string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.