我有这样"12,a,{3,4},b,c"
一个字符串,我需要将其转换成一个阵列,其中在大括号中的元素应该是一个子阵列,其结果应该是这样的更换喜欢串用字符数组阵列替换
["12","a",[3,4],"b","c"]
对于其他例如:
"12,a,b,c,{e,f}" --> ["12","a","b","c", ["e","f"]]
"{12,a},b,c,{c,d}" --> [["12","a"],"b","c", ["e","f"]]
我有这样"12,a,{3,4},b,c"
一个字符串,我需要将其转换成一个阵列,其中在大括号中的元素应该是一个子阵列,其结果应该是这样的更换喜欢串用字符数组阵列替换
["12","a",[3,4],"b","c"]
对于其他例如:
"12,a,b,c,{e,f}" --> ["12","a","b","c", ["e","f"]]
"{12,a},b,c,{c,d}" --> [["12","a"],"b","c", ["e","f"]]
你可以试试这个代码:
a = "{12,a},b,c,{c,d}";
m = a.match(/{[^}]*}|[^,]+/g);
arr=[];
for (i=0; i<m.length; i++) {
if (m[i].indexOf('{') >= 0)
arr.push(m[i].replace(/[{}]/g, "").split(/,/));
else
arr.push(m[i]);
}
console.log(arr);
OUTPUT:
[[12,a],b,c,[c,d]]
var a = "12,a,{3,4},b,c,{2,3}";
var b = eval(("[" + a.replace(/{/g, '[').replace(/}/g, ']') + "]").replace(/[a-zA-Z]/g, function (all, match) { return "'" + all+ "'";}));
console.log(b)
试试这个
你可以试试这个。
var m = "{12,a},b,c,{c,d}".split(','),
result = m.reduce(function(a, b) {
if (b.indexOf('{') !== -1 || a.t.length){
a.t.push(b.replace(/\{|\}/,''));
} else {
a.array.push(b);
}
if (b.indexOf('}') !== -1){
a.array.push(a.t);
a.t = [];
}
return a ;
}, { array:[],t:[]}).array;
console.log(result);
会像这样的数组是可以接受的? '[[“12”],[“a”],[“3”,“4”],[“b”],[“c”]]'这可以表示为锯齿状的字符串数组。 –
是应该但最后 – Sarath
你在做什么? –