• Post category:JavaScript
  • Reading time:4 mins read

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

Using split() method, you can split a string using a specific separator and convert into an array. You can use string or a regular expression as separator. If we use an empty string (“”) as the separator then string will be split between each character.

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..!!

Leave a Reply