008,00801,008,00802,009,00901
像这样的数据每隔两个逗号分割成一个数组
let str = '008,00801,008,00802,009,00901';
let ar = str.split(',');
let newArray = [];
for (index in ar) {
if (index %2 != 0) {
newArray.push(ar[index-1]+','+ar[index]);
}
}
if (ar.length %2 != 0) {
newArray.push(ar[ar.length-1]);
}
console.log(newArray);
let str = "008,00801,008,00802,009,00901";
let arr = str.split(",");
let num = 2;
let newArr = arr.reduce((pre, cur, index) => {
if (index % num === 0) {
return pre.concat([arr.slice(index, index + num)]);
} else {
return pre;
}
}, []);
console.log("newarr==", newArr);
一个低效的正则
'008,00801,008,00802,009,00901'.split(/(?<=^(?:[^,]*?,[^,]*?,)*?[^,]*?,[^,]*?),/)
// ["008,00801", "008,00802", "009,00901"]
或者如果确保只包含数字和逗号的话:
'008,00801,008,00802,009,00901'.split(/(?<=^(?:\d*?,\d*?,)*?\d*?,\d*?),/)
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决