Convert comma separated string to array

2018-12-31 08:48发布

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 want to split this by comma and store in Array object

10条回答
孤独寂梦人
2楼-- · 2018-12-31 09:23

good solution for that

let obj = ['A','B','C']

obj.map((c) => { return c. }).join(', ')
查看更多
与君花间醉酒
3楼-- · 2018-12-31 09:24

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

var array = string.split(',');
查看更多
路过你的时光
4楼-- · 2018-12-31 09:26

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 ;
    }
查看更多
墨雨无痕
5楼-- · 2018-12-31 09:30

I know this question has been answered for quite a while, but I thought that my contribution would be beneficial to others researching this topic...

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 is no separator character in the string (only one item)

查看更多
登录 后发表回答