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

我有一个逗号分隔的字符串,我想将其转换为数组,以便我可以循环遍历它。

有什么内置的东西可以做到这一点吗?

例如,我有一根绳子

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

现在我想用逗号将其拆分,然后将其存储在数组中。

1310590 次浏览
var array = string.split(',');

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

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

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

注意您是否针对整数,例如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(",");

添加这样的循环,

for (a in temp ) {temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment}

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

嗯,拆分是危险的,因为字符串总是可以包含逗号。观察以下内容:

var myArr = "a,b,c,d,e,f,g,','";result = myArr.split(',');

那么你将如何解释它?你想要的结果是什么?一个数组:

['a', 'b', 'c', 'd', 'e', 'f', 'g', '\'', '\''] or['a', 'b', 'c', 'd', 'e', 'f', 'g', ',']

即使你逃避逗号,你也会有问题。

我很快地把它放在一起:

(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);

将逗号分隔的字符串传递给此函数,它将返回一个数组,如果未找到逗号分隔的字符串,则它将返回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 elseif (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;}

这是一个将字符串转换为数组的函数,即使列表中只有一个项目(没有分隔符):

function listToAray(fullString, separator) {var fullArray = [];
if (fullString !== undefined) {if (fullString.indexOf(separator) == -1) {fullArray.push(fullString);} else {fullArray = fullString.split(separator);}}
return fullArray;}

像这样使用它:

var myString = 'alpha,bravo,charlie,delta';var myArray = listToArray(myString, ',');myArray[2]; // charlie
var yourString = 'echo';var yourArray = listToArray(yourString, ',');yourArray[0]; // echo

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

请注意以下内容:

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

将提醒1

我遇到了类似的问题,但更复杂,因为我需要将CSV文件转换为数组数组(每行是一个数组元素,其中包含一个由逗号分隔的数组)。

最简单的解决方案(我打赌更安全)是使用PapaParse,它有一个“无标头”选项,可以将CSV文件转换为数组数组,另外,它会自动检测“,”作为我的分隔符。

另外,它在鲍尔中注册,所以我只需要:

bower install papa-parse --save

然后在我的代码中使用它,如下所示:

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

我真的很喜欢它。

返回函数

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

它的接受字符串和对象字符串:

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+ "];")());

jsfiddlehttps://jsfiddle.net/7ne9L4Lj/1/

一个很好的解决方案:

let obj = ['A','B','C']
obj.map((c) => { return c. }).join(', ')
let str = "January,February,March,April,May,June,July,August,September,October,November,December"
let arr = str.split(',');

这将导致:

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

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

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

这:

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

使用:

str = arr.join(',')

最短

str.split`,`

var str = "January,February,March,April,May,June,July,August,September,October,November,December";
let arr = str.split`,`;
console.log(arr);

对于逗号分隔字符串的字符串数组:

let months = ["January","Feb"];let monthsString = months.join(", ");

正如@oportocala提到的,空字符串不会导致预期的空数组。

为了反击,做:

str.split(',').map(entry => entry.trim()).filter(entry => entry)

对于预期整数的数组,执行:

str.split(',').map(entry => parseInt(entry)).filter(entry => typeof entry ==='number')

我制作了PHP脚本将字符串转换为数组,您可以在浏览器中运行它,所以很容易

<form method="POST"><div><label>String</label> <br><input name="string" type="text"></div><div style="margin-top: 1rem;"><button>konvert</button></div></form>
<?php
$string = @$_POST['string'];
if ($string) {$result = json_encode(explode(",",$string));echo " '$result' <br>";}?>
let myString = "January,February,March,April,May,June,July,August,September,October,November,December";const temp=myString .split(",");console.log(temp);

输出:- ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]

非常简单,您可以为此使用分裂默认javascript函数。

如果用户通过添加额外的空格来拼写错误。您可以使用这样的东西。

tags: foo,  zar, gar
const stringToArr = (string) => {return string.trim.split(",");};

升级str.split(',')

简单的str.split(',')没有太多的智慧。这里有一些针对不同需求的升级。您可以根据自己的需求自定义功能。

const str = "a, b,c,  d  ,e  ,f,,g"const num = "1, 2,3,  4  ,5  ,6,,7.495"const mix = "a, 2,3,  d  ,5  ,f,,7.495,g"
console.log(    str.split(',')) // spaces NOT trimmed, empty values included// ["a", " b", "c", "  d  ", "e  ", "f", "", "g"]
console.log(    str.split(/[ ,]+/)) // spaces trimmed, empty values skipped// ["a", "b", "c", "d", "e", "f", "g"]
console.log(    str.split(/\s*,\s*/)) // spaces trimmed, empty values NOT skipped// ["a", "b", "c", "d", "e", "f", "", "g"]
console.log(    num.split(',').map(Number)) // numbers, empty values default to zero// [1, 2, 3, 4, 5, 6, 0, 7.495]
console.log(    num.split(/[ ,]+/).map(Number)) // numbers, skips empty values// [1, 2, 3, 4, 5, 6, 7.495]
console.log(    mix.split(/\s*,\s*/).map(x => (x === '') ? '' : (isNaN(Number(x)) ? x : Number(x)) )) // mixed values, empty values included// ["a", 2, 3, "d", 5, "f", "", 7.495, "g"]

使用JSON.parse

它可能感觉有点像黑客,但它很简单,并且被大多数Javascript引擎高度优化。

它有一些其他优点,例如支持嵌套列表。但也有缺点,例如要求输入正确格式化JSON。

通过使用类似于上面使用string.splitstring.replace,您可以修复输入。在下面的前两个示例中,我自定义了处理空值的方式:

const num = "1, 2,3,  4  ,5  ,6,,7.495"const mix = "a, 2,3,  d  ,5  ,f,7.495,g"
console.log(    JSON.parse('['+num.replace(/,\s*,/,',0,')+']')) // numbers, empty values default to zero// [1, 2, 3, 4, 5, 6, 0, 7.495]
console.log(    JSON.parse('['+num.replace(/,\s*,/,',')+']')) // numbers, skips empty values// [1, 2, 3, 4, 5, 6, 7.495]
console.log(    JSON.parse('['+mix.replace(/(^|,)\s*([^,]*[^0-9, ][^,]*?)\s*(?=,|$)/g,'$1"$2"')+']')) // mixed values, will ERROR on empty values// ["a", 2, 3, "d", 5, "f", "7.495", "g"]  

最简单的方法:

let myStr = '1, 2, 3, 4, 5, 7, 8';
const stringToArr = (myStr) => {return myStr.split(',').map(x => x.trim());};