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

后端 未结 15 1599
温柔的废话
温柔的废话 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条回答
  •  Happy的楠姐
    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;
    }
    

提交回复
热议问题