Convert string with commas to array

后端 未结 18 885
执念已碎
执念已碎 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:31

    More "Try it Yourself" examples below.

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

    Tip: If an empty string ("") is used as the separator, the string is split between each character.

    Note: The split() method does not change the original string.

    var res = str.split(",");
    
    0 讨论(0)
  • 2020-11-22 12:32

    Split it on the , character;

    var string = "0,1";
    var array = string.split(",");
    alert(array[0]);
    
    0 讨论(0)
  • 2020-11-22 12:32

    If the string is already in list format, you can use the JSON.parse:

    var a = "['a', 'b', 'c']";
    a = a.replace(/'/g, '"');
    a = JSON.parse(a);
    
    0 讨论(0)
  • 2020-11-22 12:32

    Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.

    it('convert string to array', function () {
      expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
    });
    
    0 讨论(0)
  • 2020-11-22 12:35

    I remove the characters '[',']' and do an split with ','

    let array = stringObject.replace('[','').replace(']','').split(",").map(String);
    
    0 讨论(0)
  • 2020-11-22 12:36

    You can use split

    Reference: http://www.w3schools.com/jsref/jsref_split.asp

    "0,1".split(',')

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