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.
- How to convert an Array to a String in JavaScript
- How to convert a string to an integer in JavaScript
- ES6 Rest Parameter in JavaScript
- JavaScript Array methods Splice vs Slice
- How to use Map, Filter, and Reduce 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
- Split using comma separator
- Split using comma separator and limit
- 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..!!