Convert a Comma Separated String to Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

Convert a Comma Separated String to Array #

To convert a comma separated string into an array, call the split() method on the string, passing it a comma as a parameter - str.split(','). The split method will divide the string on each comma and return the substrings in an array.

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 parameter 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 array only contains the words and no empty spaces.

Note that 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 pass the condition in the function.

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

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee