Javascript 如何将逗号分隔的字符串转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2858121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:13:50  来源:igfitidea点击:

How to convert a comma separated string to an array?

javascriptstringsplit

提问by Blankman

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.

现在我想用逗号分割它,然后将它存储在一个数组中。

回答by Matchu

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

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

MDN 参考,主要有助于limit参数可能出现的意外行为。(提示:结果"a,b,c".split(",", 2)["a", "b"],而不是["a", "b,c"]。)

回答by pop

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.

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

回答by Justme

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

随意使用/编辑它:)

回答by Jakkwylde

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

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

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

回答by user1386213

Note that the following:

请注意以下几点:

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

will alert 1

将警报 1

回答by BJ Patel

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

将您的逗号分隔字符串传递给此函数,它将返回一个数组,如果未找到逗号分隔的字符串,则将返回 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 { 
  // string has only one value, can also check the length of the string or time and cross-check too. 
                    ResultArray = [CommaSepStr]; 
              }
        }
       return ResultArray ;
    }

回答by Andi AR

Return function

返回功能

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

its accept string and 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/

回答by Kabb5

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 splitthrows out an error if there is no separator character in the string (only one item)

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

回答by Diego Pamio

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/),它有一个“无标题”选项,可以将 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.

我真的很喜欢它。

回答by Mubeen Khan

let str = "January,February,March,April,May,June,July,August,September,October,November,December"

let arr = str.split(',');

it will result:

它会导致:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

and if you want to convert following to:

如果您想将以下内容转换为:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

this:

这个:

"January,February,March,April,May,June,July,August,September,October,November,December";

use:

用:

str = arr.join(',')