Convert comma separated String into an Array in JavaScript
In this tutorial, you will see how to convert comma separated string into an array in javaScript.
Convert comma separated String into an Array in JavaScript, JavaScript String split() Method, JavaScript | String split(), Convert String to Array with JavaScript’s String split Method, Convert string with commas to array, String.prototype.split(), Using JavaScript’s Array Methods on Strings, How to split a string into an array, String Array in JavaScript.
Checkout more articles on 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:
1 | 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
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.
1 2 3 4 5 | 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.
1 2 3 4 5 6 7 | 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.
1 2 3 4 5 | 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!