Convert string with commas to array

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

提交回复
热议问题