gpt4 book ai didi

javascript - 如何将字符串分成组?

转载 作者:行者123 更新时间:2023-11-28 15:03:48 25 4
gpt4 key购买 nike

假设我有一个随机字符串:

string = "223243902345676";

我如何在 Javascript 中将此字符串分成四个组,以获得:

string = ['0223','2439','0234','5676'];

最佳答案

请遵循此代码

// 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"]

关于javascript - 如何将字符串分成组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40035025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com