[英]Converting a comma separated string into an array
I have the following string: 我有以下字符串:
'"alpha", "beta", "gamma", "delta"'
How can I convert the string into an array such that: 如何将字符串转换为数组,例如:
array = ["alpha", "beta", "gamma", "delta"];
So I can call on individual elements of the array such that: 因此,我可以调用数组的各个元素,例如:
array[0] = "alpha"
I've attempted using str.split but am unsure of the correct usage to separate the quotation marks and commas. 我曾尝试使用str.split,但不确定将引号和逗号分开的正确用法。
Modify the string so that it's valid JSON , then JSON.parse()
it: 修改字符串,使其为有效JSON ,然后将其转换为
JSON.parse()
:
var str = '"alpha", "beta", "gamma", "delta"'; var json = '[' + str + ']'; var array = JSON.parse(json); console.log(array[0])
这将为您解决问题:
str.replace(/\\"/g, '').split(', ')
Remove the quotations and spaces, then split on the comma 删除引号和空格,然后以逗号分隔
var str = '"alpha", "beta", "gamma", "delta"';
var strArray = str.replace(/"/g, '').replace(/ /g, '').split(',');
Possibly more efficient than the others; 可能比其他方法更有效; trim off the 1st and last
"
characters and split on the ", "
sequence. 修剪第一个和最后一个
"
字符,并按", "
顺序分割。
var str = '"alpha", "beta", "gamma", "delta"'; var str2 = str.substr(1, str.length - 2).split('", "'); console.log(str2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.