Convert a comma-separated String to an Array in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
5 min

banner

# Table of Contents

  1. Convert a comma-separated String to an Array in JavaScript
  2. Handling a comma followed by a variable number of spaces
  3. Convert a comma-separated string to an Array of Numbers

# Convert a comma-separated String to an Array in JavaScript

Use the String.split() method to convert a comma-separated string to an array.

The split() method will split the string on each occurrence of a comma and will return an array containing the results.

index.js
// ๐Ÿ‘‡๏ธ to an array of strings const str = 'bobby,hadz,com'; const arr = str.split(','); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(arr); console.log(arr[0]); // ๐Ÿ‘‰๏ธ bobby console.log(arr[1]); // ๐Ÿ‘‰๏ธ hadz // ----------------------------------------- // ๐Ÿ‘‡๏ธ to an array of numbers const str2 = '1,2,3,4,5,6'; const arr2 = str2.split(',').map(Number); console.log(arr2); // ๐Ÿ‘‰๏ธ [ 1, 2, 3, 4, 5, 6 ]

convert comma separated string to an array

The code for this article is available on GitHub
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.

If the words in your string are separated by a comma followed by a space, pass a comma and a space as the separator to the split() method.

index.js
const str = 'bobby, hadz, com'; const arr = str.split(', '); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(arr);

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

index.js
const str = ''; const arr = str.split(','); console.log(arr); // ๐Ÿ‘‰๏ธ ['']

If you want to get an empty array when the string is empty, use the Array.filter() 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 a new array containing only the elements that meet the condition.

# Handling a comma followed by a variable number of spaces

If your string might contain a comma followed by one or more spaces, pass a regular expression to the String.split() method.

index.js
const str = 'bobby,hadz,com'; function commaSeparatedToArray(str) { return str.split(/[ ,]+/); } // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby,hadz,com')); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby,,hadz,,com')); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby, hadz, com')); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(commaSeparatedToArray('bobby, hadz, com'));

handling comma followed by variable number of spaces

The code for this article is available on GitHub

The forward slashes / / mark the beginning and end of the regular expression.

The brackets [] are called a character class and match the specified characters.

In our case, spaces and commas.

The plus + matches the preceding item (spaces and commas) one or more times.

In its entirety, the regular expression splits the string by one or more consecutive spaces and commas.

If you need to get an array of numbers, use the map() method.

index.js
const str = 'bobby,hadz,com'; function commaSeparatedToArray(str) { return str.split(/[ ,]+/).map(Number); } // ๐Ÿ‘‡๏ธ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1,2,3')); // ๐Ÿ‘‡๏ธ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1,,2,,3')); // ๐Ÿ‘‡๏ธ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1, 2, 3')); // ๐Ÿ‘‡๏ธ [ 1, 2, 3 ] console.log(commaSeparatedToArray('1, 2, 3'));

The function we passed to the Array.map() method gets called with each element in the array.

On each iteration, we use the Number constructor to convert the current value to a number and return the result.

The map() method returns a new array containing the values returned from the callback function.

# Convert a comma-separated string to an Array of Numbers

To convert a comma-separated string to a numeric array:

  1. Use the split() method to split the string into an array of digits.
  2. Use the map() method to iterate over the array.
  3. Convert each string to a number and return the result.
index.js
const str = '12,34,56,78,9'; const arr = str.split(',').map(element => { return Number(element); }); // ๐Ÿ‘‡๏ธ [12, 34, 56, 78, 9] console.log(arr);

convert comma separated string to array of numbers

The code for this article is available on GitHub
If your string might contain non-numeric values or empty values between commas, scroll down to the next solution.

We used the String.split() method to split the string on each comma.

The split() method divides a string into an array of substrings based on a separator.

By splitting the string on each comma, we get an array containing the digits.

index.js
const str = '12,34,56,78,9'; // ๐Ÿ‘‡๏ธ๏ธ ['12', '34', '56', '78', '9'] console.log(str.split(','));

The last step is to convert each string in the array to a number.

The function we passed to the Array.map() method gets called with each element in the array.

On each iteration, we use the Number() constructor to convert the string to a number and return the result.

The map() method returns a new array containing the values returned from the callback function.

However, if your string contains empty values between commas, non-numeric characters or punctuation, you have to filter the results first.
index.js
const str = '12,34,,a,!,56,,,78,9'; const arr = str .split(',') .filter(element => { if (element.trim() === '') { return false; } return !isNaN(element); }) .map(element => { return Number(element); }); // ๐Ÿ‘‡๏ธ [12, 34, 56, 78, 9] console.log(arr);
The code for this article is available on GitHub

In this example, our string contains empty values between the commas, some letters and punctuation.

The function we passed to the Array.filter() method gets called with each element in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

We first check if the element is equal to an empty string or contains only whitespace and return false if it does.

Finally, we use the isNaN() function to check if the provided string is not a number.

We used the logical NOT (!) operator to negate the value returned from the isNaN() function.

The isNaN (is not a number) method tries to convert the string to a number and returns true if it fails.

index.js
console.log(isNaN('hello')); // ๐Ÿ‘‰๏ธ true console.log(isNaN('')); // ๐Ÿ‘‰๏ธ false console.log(isNaN(' ')); // ๐Ÿ‘‰๏ธ false
This seems quite confusing at first, but the isNaN function converts an empty string or a string containing spaces to a number and gets a value of 0, so it returns false.
index.js
console.log(Number('')); // ๐Ÿ‘‰๏ธ 0 console.log(Number(' ')); // ๐Ÿ‘‰๏ธ 0

This is why we used the trim() method to trim the string and verify that it's not an empty string.

We know that if the isNaN function gets called with a string that contains at least 1 character and returns true, the string is NOT a valid number.

Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false, then the string is a valid number.

Here are some more examples of calling isNaN with strings.

index.js
console.log(isNaN('123')); // ๐Ÿ‘‰๏ธ false console.log(isNaN('1.23')); // ๐Ÿ‘‰๏ธ false console.log(isNaN('1,23')); // ๐Ÿ‘‰๏ธ true console.log(isNaN('123test')); // ๐Ÿ‘‰๏ธ true
The code for this article is available on GitHub

Only numeric values are contained in the array that the filter() method returns.

This enables us to call the map() method on the array to convert each string to a number.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev