How to convert a comma separated string to an array?

How to convert a comma separated string to an array?

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 e.g. I have this string
var str = “January,February,March,April,May,June,July,August,September,October,November,December”;

now I want to split this by the comma, and then store it in an Array object.

Solutions/Answers:

Solution 1:

var array = string.split(',');

MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)

Solution 2:

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// this will return an array with strings "1", "2", etc.
temp = str.split(",");

adding a loop like this

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.

Solution 3:

Hmm split is dangerous imho as a string can always contain a comma, observe the following:

var myArr = "a,b,c,d,e,f,g,','";
result = myArr.split(',');

So how would you interperate that? and what do you WANT the result to be? an array with:

['a', 'b', 'c', 'd', 'e', 'f', 'g', '\'', '\''] or 
['a', 'b', 'c', 'd', 'e', 'f', 'g', ',']

even if you escape the comma you’d have a problem.

Quickly fiddled this together:

(function($) {
    $.extend({
        splitAttrString: function(theStr) {
            var attrs = [];

            var RefString = function(s) {
                this.value = s;
            };
            RefString.prototype.toString = function() {
                return this.value;
            };
            RefString.prototype.charAt = String.prototype.charAt;
            var data = new RefString(theStr);

            var getBlock = function(endChr, restString) {
                var block = '';
                var currChr = '';
                while ((currChr != endChr) && (restString.value !== '')) {
                    if (/'|"/.test(currChr)) {
                        block = $.trim(block) + getBlock(currChr, restString);
                    }
                    else if (/\{/.test(currChr)) {
                        block = $.trim(block) + getBlock('}', restString);
                    }
                    else if (/\[/.test(currChr)) {
                        block = $.trim(block) + getBlock(']', restString);
                    }
                    else {
                        block += currChr;
                    }
                    currChr = restString.charAt(0);
                    restString.value = restString.value.slice(1);
                }
                return $.trim(block);
            };

            do {
                var attr = getBlock(',', data);
                attrs.push(attr);
            }
            while (data.value !== '');
            return attrs;
        }
    });
})(jQuery);

Feel free to use / edit it 🙂

Solution 4:

The split() method is used to split a string into an array of substrings, and returns the new array.

var array = string.split(',');

Solution 5:

Note that the following:

 var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);

will alert 1

Solution 6:

Pass your comma Separated string into this function and it will return array, and if not comma separated string found then will return null.

 function SplitTheString(CommaSepStr) {
       var ResultArray = null; 

        if (CommaSepStr!= null) {
            var SplitChars = ',';
            if (CommaSepStr.indexOf(SplitChars) >= 0) {
                ResultArray = CommaSepStr.split(SplitChars);

            }
        }
       return ResultArray ;
    }