How to Convert a Comma-Separated String to an Array in JavaScript?

Depending on whether your comma-separated string has whitespaces, you can do the following to convert it into an array:

Convert Comma-Separated String With No Spaces Into an Array

You can convert a JavaScript comma-separated string (which has no spaces) into an array by using the String.prototype.split() method, for example, like so:

const str = 'foo,bar,baz,qux';

console.log(str.split(',')); // ['foo', 'bar', 'baz', 'qux']

Convert Comma-Separated String With Set Sequence of Repeating Spaces Into an Array

If the comma-separated string has a known number of spaces in a repeating sequence (e.g. ", "), then you can simply specify it as the delimiter to the String.prototype.split() method, for example, like so:

const str = 'foo, bar, baz, qux';

console.log(str.split(', ')); // ['foo', 'bar', 'baz', 'qux']

Convert Comma-Separated String With Unknown Whitespaces Into an Array

If your string has unknown number of whitespaces before/after in any order/number, then you can use Array.prototype.map() to iterate over each item in the resulting array (from String.prototype.split()) and use String.prototype.trim() to trim any whitespaces:

const str = '  foo ,   bar,baz,  qux   ';
const arr = str.split(',').map((item) => item.trim());

console.log(arr); // ['foo', 'bar', 'baz', 'qux']

This also works as expected when there's a set sequence of repeating spaces in the string. For example:

const str = 'foo, bar, baz, qux';
const arr = str.split(',').map((item) => item.trim());

console.log(arr); // ['foo', 'bar', 'baz', 'qux']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.