How can I convert a comma-separated string to an array?

后端 未结 15 1415
温柔的废话
温柔的废话 2020-11-22 02:37

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

相关标签:
15条回答
  • 2020-11-22 02:56

    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.

    0 讨论(0)
  • 2020-11-22 02:57

    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 interpret 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.

    I 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);
    
    0 讨论(0)
  • 2020-11-22 02:59
    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"].)

    0 讨论(0)
  • 2020-11-22 03:07

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

    function splitTheString(CommaSepStr) {
        var ResultArray = null;
    
        // Check if the string is null or so.
        if (CommaSepStr!= null) {
    
            var SplitChars = ',';
    
            // Check if the string has comma of not will go to else
            if (CommaSepStr.indexOf(SplitChars) >= 0) {
                ResultArray = CommaSepStr.split(SplitChars);
    
            }
            else {
    
                // The string has only one value, and we can also check
                // the length of the string or time and cross-check too.
                ResultArray = [CommaSepStr];
            }
        }
        return ResultArray;
    }
    
    0 讨论(0)
  • 2020-11-22 03:07

    A good solution for that:

    let obj = ['A','B','C']
    
    obj.map((c) => { return c. }).join(', ')
    
    0 讨论(0)
  • For an array of strings to a comma-separated string:

    let months = ["January","Feb"];
    let monthsString = months.join(", ");
    
    0 讨论(0)
提交回复
热议问题