How to Convert Comma Separated String into Array using JavaScript?

To convert a comma separated string into an array in JavaScript, you can use the string.split() method. The split() method lets you split a string at a given character and returns an array as a result.

Here is its syntax:

str.split(separator, limit)

So, if you want to split the string at each occurrence of a comma(,), you have to pass a comma(',') as a separator to the split() method.

See the following example:

let str = 'apple,banana,mango,orange';

let arr = str.split(',');
console.log(arr);

// Output 👇
// ["apple", "banana", "mango", "orange"]

If the string you want to split has spaces after commas, then in the separator, you have to put a space after the comma too.

See the following example:

let str = 'apple, banana, mango, orange';

let arr = str.split(', ');
console.log(arr);

// Output 👇
// ["apple", "banana", "mango", "orange"]

In case, the string we want to split at each comma is empty, then the resulting array will not be empty, instead, it will contain an empty string.

See the following example:

let str = '';

let arr = str.split(',');
console.log(arr);

// Output 👇
// [""]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts