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

后端 未结 15 1416
温柔的废话
温柔的废话 2020-11-22 02:37

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

相关标签:
15条回答
  • 2020-11-22 03:10

    Shortest

    str.split`,`
    

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

    0 讨论(0)
  • 2020-11-22 03:11

    You can try the following snippet:

     var str = "How,are,you,doing,today?";
        var res = str.split(",");
        console.log("My Result:", res)
    
    0 讨论(0)
  • 2020-11-22 03:16

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

    var array = string.split(',');
    
    0 讨论(0)
  • 2020-11-22 03:17

    As @oportocala mentions, an empty string will not result in the expected empty array.

    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')
    
    0 讨论(0)
  • 2020-11-22 03:20

    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/

    0 讨论(0)
  • 2020-11-22 03:20

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

    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.

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

    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.

    0 讨论(0)
提交回复
热议问题