Code Premix

How to convert comma separated String into an Array in JavaScript

๐Ÿ“…June 22, 2021
๐Ÿ—JavaScript

In this tutorial, you will see how to convert comma separated string into an array in JavaScript.

Syntax:

str.split(separator, limit)

Here, separator parameter is used for splitting the string. Itโ€™s optional parameter. limit parameter that specifies the number of splits, items after the split limit will not be added in the array.

Example: Convert comma separated String into an Array

  1. Split using comma separator
  2. Split using comma separator and limit
  3. Split using empty string separator

1. Split using comma separator

If you have a comma separated script and want to split it by comma then you can simply use comma separator in the first argument of the split method.

var str = "Rose,Lotus,Sunflower,Marogold,Tulip,Jasmine";
var arr = str.split(',');
console.log(arr);

// Output: ["Rose", "Lotus", "Sunflower", "Marogold", "Tulip", "Jasmine"]

2. Split using comma separator and limit

You can use the limit parameter to split string into an array and also retrieve the individual name.

var str = "Rose,Lotus,Sunflower,Marogold,Tulip,Jasmine";
var arr = str.split(",", 3);
console.log(arr);
// Output: ["Rose", "Lotus", "Sunflower"]

console.log(arr[0]);
// Output: Rose

3. Split using empty string separator

If we pass empty string (โ€œโ€) as the separator then each character will be splitted and converted into the array.

var str = "How are you?";
var arr = str.split("");
console.log(arr);

// Output: ["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", "?"]

Thank you for reading. Happy Coding..!!