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
Note that the following:
var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);
will alert 1
let str = "January,February,March,April,May,June,July,August,September,October,November,December"
let arr = str.split(',');
it will result:
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
and if you want to convert following to:
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
this:
"January,February,March,April,May,June,July,August,September,October,November,December";
use:
str = arr.join(',')
Here is a function that will convert a string to an array, even if there is only one item in the list (no separator character):
function listToAray(fullString, separator) {
var fullArray = [];
if (fullString !== undefined) {
if (fullString.indexOf(separator) == -1) {
fullAray.push(fullString);
} else {
fullArray = fullString.split(separator);
}
}
return fullArray;
}
Use it like this:
var myString = 'alpha,bravo,charlie,delta';
var myArray = listToArray(myString, ',');
myArray[2]; // charlie
var yourString = 'echo';
var yourArray = listToArray(yourString, ',');
yourArray[0]; // echo
I created this function because split
throws out an error if there isn't any separator character in the string (only one item).