假设我有一个随机字符串:
string = "223243902345676";
如何在Javascript中将此字符串分成四个一组,以便:
string = ['0223','2439','0234','5676'];
答案 0 :(得分:2)
请遵循此代码
// 0. declare input value
const input = '223243902345676'
const inputs = input.split('')
// 1. get how many zero padding
const padding = 4 - inputs.length % 4
// 2. get zero padding array
const zeroItems = []
for (let i = 0; i < padding; i++) {
zeroItems.push(0)
}
// 3. concat 2 array (now we get items with zero padding)
const mergeItems = zeroItems.concat(inputs)
// 4. get each item of 4 characters and put to result
const result = []
const LEN = mergeItems.length / 4
for (let i = 0; i < mergeItems.length; i += LEN) {
const resultItems = mergeItems.slice(i, i + LEN)
result.push(resultItems.join(''))
}
console.log(result) // print ["0223", "2439", "0234", "5676"]
&#13;
答案 1 :(得分:1)
我将这样做。
yourString.match(/.{1,4}/g);
答案 2 :(得分:1)
这是另一种带有'0'填充的方法;
let string = '223243902345676';
const fourDigits = /\d{4}/g;
const result = string
.split('')
.reduce((prev, curr, index) => {
let padding = '0' + prev;
return (index === 1) ? padding += curr : prev += curr;
})
.match(fourDigits);
console.log(result);
// ['0223','2439','0234','5676'];