Convert string with commas to array

后端 未结 18 886
执念已碎
执念已碎 2020-11-22 12:08

How can I convert a string to a JavaScript array?

Look at the code:

var string = \"0,1\";
var array = [string];
alert(array[0]);

In

相关标签:
18条回答
  • 2020-11-22 12:24

    var i = "[{a:1,b:2}]",
        j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
        k = JSON.parse(j);
    
    console.log(k)

    // => declaring regular expression

    [a-zA-Z0-9] => match all a-z, A-Z, 0-9

    (): => group all matched elements

    $1 => replacement string refers to the first match group in the regex.

    g => global flag

    0 讨论(0)
  • 2020-11-22 12:24

    Example using Array.filter:

    var str = 'a,b,hi,ma,n,yu';
    
    var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');
    
    0 讨论(0)
  • 2020-11-22 12:27

    Another option using the ES6 is using Spread syntax.

    var convertedArray = [..."01234"];

    var stringToConvert = "012";
    var convertedArray  = [...stringToConvert];
    console.log(convertedArray);

    0 讨论(0)
  • 2020-11-22 12:28

    This is easily achieved in ES6;

    You can convert strings to Arrays with Array.from('string');

    Array.from("01")
    

    will console.log

    ['0', '1']
    

    Which is exactly what you're looking for.

    0 讨论(0)
  • 2020-11-22 12:28

    use the built-in map function with an anonymous function, like so:

    string.split(',').map(function(n) {return Number(n);});
    

    [edit] here's how you would use it

    var string = "0,1";
    var array = string.split(',').map(function(n) {
        return Number(n);
    });
    alert( array[0] );
    
    0 讨论(0)
  • 2020-11-22 12:31

    For simple array members like that, you can use JSON.parse.

    var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
    
    var array = JSON.parse("[" + listValues + "]");
    

    This gives you an Array of numbers.

    now you variable value is like array.length=1

    Value output

    array[0].ComplianceTaskID
    array[0].RequirementTypeID
    array[0].MissedRequirement
    array[0].TimeOverdueInMinutes
    
    0 讨论(0)
提交回复
热议问题