How to Convert a Comma-Separated String into Array

There is a built-in JavaScript method which you can use and convert a comma-separated string into an array.

The split() method splits a string using a specific separator such as comma (,).

Use a comma separator in the first argument of the split method if you want to split it by comma:

Javascript arrays split method
let str = "Rome,Moscow,Paris,Madrid,Prague,Milan"; let arr = str.split(','); console.log(arr);

Use the limit parameter to split a string into an array and also get the individual name.

Javascript arrays split method
let str = "Rome,Moscow,Paris,Madrid,Prague,Milan"; let arr = str.split(",", 4); console.log(arr); // Output: ["Rome", "Moscow", "Paris", "Madrid"] console.log(arr[0]);// Output: ["Rome"]

If you pass an empty string, each character will be splitted and converted into an array:

Javascript arrays split method
let str = "W3docs.com"; let arr = str.split(""); console.log(arr);

The split() method

The split() method is called to split a string into an array of substrings and to return a new array. The split() method cuts a string into an ordered set of substrings and puts these substrings into an array returning a new array.