我有一个可变字符串mymvariable
其中包含:
864827,,,34200,Sète ,,,445958,,,30220,AIGUES MORTES,,,169807,,,34570,PIGNAN,,,546049,,,13006,MARSEILLE,,
我想将此字符串转换为这样的数组:
1 864827,,,34200,Sète ,,,
2 445958,,,30220,AIGUES MORTES,,,
3 169807,,,34570,PIGNAN,,,
4 546049,,,13006,MARSEILLE,,
我尝试使用:
var array = myvariable.split(",");
但是当我做一个数组[0]时,我会得到第一个字段:
864827
当我像这样做array [0]时,我希望有第一行:
1 864827 ,,, 34200,塞特,,,
是否可以像这样格式化字符串?
谢谢
答案 0 :(得分:4)
您可以拆分数组,缩小数组并为每7个项目构建子数组。
var string = '864827,,,34200,Sète ,,,445958,,,30220,AIGUES MORTES,,,169807,,,34570,PIGNAN,,,546049,,,13006,MARSEILLE,,',
array = string
.split(',')
.reduce((r, s, i) => r.concat([i % 7 ? r.pop().concat(s) : [s]]), []);
console.log(array[0]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
使用regexp的简单解决方案:
const str = "864827,,,34200,Sète ,,,445958,,,30220,AIGUES MORTES,,,169807,,,34570,PIGNAN,,,546049,,,13006,MARSEILLE,,"
const array = str.split(/(\d+,,,\d+,[a-zA-Zéàêè ]+\s*,,,?)/).filter(Boolean);
console.log(array);