简体   繁体   English

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

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

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 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.现在我想用逗号分隔它,然后将它存储在一个数组中。

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

MDN reference , mostly helpful for the possibly unexpected behavior of the limit parameter. MDN 参考,对limit参数可能出现的意外行为很有帮助。 (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"] , not ["a", "b,c"] .) (提示: "a,b,c".split(",", 2)出现在["a", "b"]中,而不是["a", "b,c"]中。)

Watch out if you are aiming at integers, like 1,2,3,4,5.请注意您是否针对整数,例如 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.如果您打算在拆分字符串后将数组的元素用作整数而不是字符串,请考虑将它们转换为整数。

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.将返回一个包含整数的数组,而不是字符串。

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 interpret 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.即使你避开逗号,你也会遇到问题。

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

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

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

Note that the following:请注意以下事项:

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

will alert 1会提醒 1

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

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) {
      fullArray.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 isn't any separator character in the string (only one item).我创建了这个函数,因为如果字符串中没有任何分隔符(只有一个项目), split会抛出一个错误。

Upgraded str.split(',')升级str.split(',')

The simple str.split(',') doesn't have much smarts.简单的str.split(',')没有太多的聪明之处。 Here are some upgrades for different needs.以下是针对不同需求的一些升级。 You can customize the functionality to your heart's content.您可以根据自己的喜好自定义功能。

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

Using JSON.parse使用JSON.parse

It may feel like a bit of a hack, but it's simple and highly optimized by most Javascript engines.它可能感觉有点像 hack,但它很简单,并且被大多数 Javascript 引擎高度优化。

It has some other advantages such as support for nested lists.它还有一些其他优点,例如支持嵌套列表。 But there are disadvantages, such as requiring the input to be properly formatted JSON.但也有缺点,例如要求输入格式正确的 JSON。

By using string.replace similar to how I used string.split above, you can fix the input.通过使用类似于我上面使用string.splitstring.replace ,您可以修复输入。 In the first two examples below, I customize how I want empty values handled:在下面的前两个示例中,我自定义了如何处理空值:

 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 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(',')

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/

I had a similar issue, but more complex as I needed to transform a CSV file 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 which has a "no-header" option that transform the CSV file into an array of arrays, plus, it automatically detected the "," as my delimiter.最简单的解决方案(我敢打赌也更安全)是使用PapaParse ,它有一个“无标题”选项,可将 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.我真的很喜欢它。

A good solution for that:一个很好的解决方案:

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

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

Shortest最短的

str.split`,`

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

You can try the following snippet:您可以尝试以下代码段:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

As @oportocala mentions, an empty string will not result in the expected empty array.正如@oportocala 提到的,空字符串不会导致预期的空数组。

So to counter, do:因此,要反击,请执行以下操作:

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

For an array of expected integers, do:对于预期整数数组,请执行以下操作:

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

I made php script to convert string to array, and you can run it into your browser, so is easy我制作了将字符串转换为数组的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);

Output:- ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]输出:- [“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月” "]

Very simple you can use the split default javascript function for this.非常简单,您可以为此使用拆分默认 javascript 函数。

If the user makes a typo by adding an extra space.如果用户通过添加额外的空格来打错字。 You could use something like this.你可以使用这样的东西。

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

Easiest way to do it:最简单的方法:

let myStr = '1, 2, 3, 4, 5, 7, 8';

const stringToArr = (myStr) => {
    return myStr.split(',').map(x => x.trim());
};

var str = "January,February,March,April,May,June, July,August,September,October, November,December"; var str = "一月、二月、三月、四月、五月、六月、七月、八月、九月、十月、十一月、十二月";

var temp =str.split(",") console.log(temp); var temp =str.split(",") console.log(temp);

and output will be和 output 将是

[ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ]

For an array of strings to a comma-separated string:对于以逗号分隔的字符串的字符串数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM