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:

let str = "Rome,Moscow,Paris,Madrid,Prague,Milan";
let arr = str.split(',');

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

let str = "Rome,Moscow,Paris,Madrid,Prague,Milan";
let arr = str.split(",", 4);
// 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:

let str = "";
let arr = str.split("");

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.

Do you find this helpful?

Related articles