js分割字符串,先四位再六位再四位
这种格式的
回答:
准备数据
const cases = [ "GOAC720202EDB",
"GOAC720202MCSMGN06",
"GOAC720202MCSMGN062343456"
];
const segmentLengths = [4, 6, 4, 4];
方法一
cases.forEach(s => { const result = [...segmentLengths, Infinity]
.reduce(([start, r], length) => {
r.push(s.slice(start, start + length));
return [start + length, r];
}, [0, []])[1]
.filter(it => it)
.join(" ");
console.log(`|${result}|`);
});
方法二
function* seperateBySpace(s, segmentLengths) { let begin = 0;
for (const len of segmentLengths) {
yield s.slice(begin, begin + len);
begin += len;
if (begin > s.length) {
return;
}
}
if (begin < s.length - 1) {
yield s.slice(begin);
}
}
const segmentLengths = [4, 6, 4, 4];
cases.forEach(s => {
const result = [...seperateBySpace(s, segmentLengths)].join(" ");
console.log(`|${result}|`);
});
输出都是
|GOAC 720202 EDB||GOAC 720202 MCSM GN06|
|GOAC 720202 MCSM GN06 2343456|
回答:
substr这个
以上是 js分割字符串,先四位再六位再四位 的全部内容, 来源链接: utcz.com/p/937345.html