I have a comma-separated string that I want to convert into an array, so I can loop through it.
Is there anything built-in to do this?
For example, I have this
str.split`,`
var str = "January,February,March,April,May,June,July,August,September,October,November,December";
let arr = str.split`,`;
console.log(arr);
You can try the following snippet:
var str = "How,are,you,doing,today?";
var res = str.split(",");
console.log("My Result:", res)
The split() method is used to split a string into an array of substrings, and returns the new array.
var array = string.split(',');
As @oportocala mentions, an empty string will not result in the expected empty array.
So to counter, do:
str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)
For an array of expected integers, do:
str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')
var array = (new Function("return [" + str+ "];")());
Its accept string and objectstrings:
var string = "0,1";
var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var stringArray = (new Function("return [" + string+ "];")());
var objectStringArray = (new Function("return [" + objectstring+ "];")());
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/
I had a similar issue, but more complex as I needed to transform a CSV file into an array of arrays (each line is one array element that inside has an array of items split by comma).
The easiest solution (and more secure I bet) was to use PapaParse which has a "no-header" option that transform the CSV file into an array of arrays, plus, it automatically detected the "," as my delimiter.
Plus, it is registered in Bower, so I only had to:
bower install papa-parse --save
And then use it in my code as follows:
var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;
I really liked it.