将逗号分隔的字符串转换为数组。

时间:2021-06-19 00:20:15

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 个解决方案

#1


937  

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"].)

MDN的引用,对限制参数的可能意外行为有很大帮助。(提示:“a,b,c”。分裂("、",2)出来(“a”、“b”)不是(“a”、“b,c])。

#2


108  

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.

注意如果你的目标是整数,比如1 2 3 4 5。如果您打算将数组的元素作为整数使用,而不是在拆分字符串之后使用字符串,那么可以考虑将它们转换为这样的字符串。

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.

将返回包含整数的数组,而不是字符串。

#3


27  

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

嗯,分裂是危险的imho,因为一个字符串总是可以包含逗号,观察下面:

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 :)

请随意使用/编辑它:)

#4


19  

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

split()方法用于将字符串拆分为子字符串数组,并返回新数组。

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

#5


12  

Note that the following:

注意以下几点:

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

will alert 1

提醒1

#6


7  

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

将逗号分隔的字符串传递到这个函数中,它将返回数组,如果不是逗号分隔字符串,则返回null。

 function SplitTheString(CommaSepStr) {
       var ResultArray = null; 

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

            }
        }
       return ResultArray ;
    }

#7


5  

Return function

var array = (new Function("return [" + str+ "];")());

its accept string and objectstrings

它接受字符串和objectstrings。

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

#8


3  

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)

我创建了这个函数,因为如果字符串中没有分隔符,split抛出一个错误(只有一个项)

#9


1  

I had a similar issue, but more complex as I needed to transform a csv into an array of arrays (each line is one array element that inside has an array of items split by comma).

我有一个类似的问题,但更复杂的是,我需要将csv转换成数组的数组(每一行都是一个数组元素,里面有一个由逗号分隔的数组)。

The easiest solution (and more secure I bet) was to use PapaParse (http://papaparse.com/) which has a "no-header" option that transform the csv into an array of arrays, plus, it automatically detected the "," as my delimiter.

最简单的解决方案是使用PapaParse (http://papaparse.com/),它有一个“no-header”选项,可以将csv转换成数组,并自动检测到“,”作为我的分隔符。

Plus, it is registered in bower, so I only had to:

另外,它是在bower注册的,所以我只需要:

bower install papa-parse --save

and then use it in my code as follows:

然后在我的代码中使用它:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

I really liked it.

我真的很喜欢它。

#10


0  

good solution for that

好的解决方案

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

obj.map((c) => { return c. }).join(', ')

#1


937  

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"].)

MDN的引用,对限制参数的可能意外行为有很大帮助。(提示:“a,b,c”。分裂("、",2)出来(“a”、“b”)不是(“a”、“b,c])。

#2


108  

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.

注意如果你的目标是整数,比如1 2 3 4 5。如果您打算将数组的元素作为整数使用,而不是在拆分字符串之后使用字符串,那么可以考虑将它们转换为这样的字符串。

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.

将返回包含整数的数组,而不是字符串。

#3


27  

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

嗯,分裂是危险的imho,因为一个字符串总是可以包含逗号,观察下面:

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 :)

请随意使用/编辑它:)

#4


19  

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

split()方法用于将字符串拆分为子字符串数组,并返回新数组。

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

#5


12  

Note that the following:

注意以下几点:

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

will alert 1

提醒1

#6


7  

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

将逗号分隔的字符串传递到这个函数中,它将返回数组,如果不是逗号分隔字符串,则返回null。

 function SplitTheString(CommaSepStr) {
       var ResultArray = null; 

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

            }
        }
       return ResultArray ;
    }

#7


5  

Return function

var array = (new Function("return [" + str+ "];")());

its accept string and objectstrings

它接受字符串和objectstrings。

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

#8


3  

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)

我创建了这个函数,因为如果字符串中没有分隔符,split抛出一个错误(只有一个项)

#9


1  

I had a similar issue, but more complex as I needed to transform a csv into an array of arrays (each line is one array element that inside has an array of items split by comma).

我有一个类似的问题,但更复杂的是,我需要将csv转换成数组的数组(每一行都是一个数组元素,里面有一个由逗号分隔的数组)。

The easiest solution (and more secure I bet) was to use PapaParse (http://papaparse.com/) which has a "no-header" option that transform the csv into an array of arrays, plus, it automatically detected the "," as my delimiter.

最简单的解决方案是使用PapaParse (http://papaparse.com/),它有一个“no-header”选项,可以将csv转换成数组,并自动检测到“,”作为我的分隔符。

Plus, it is registered in bower, so I only had to:

另外,它是在bower注册的,所以我只需要:

bower install papa-parse --save

and then use it in my code as follows:

然后在我的代码中使用它:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

I really liked it.

我真的很喜欢它。

#10


0  

good solution for that

好的解决方案

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

obj.map((c) => { return c. }).join(', ')