gpt4 book ai didi

javascript - JS中如何将一个字符串分割成2个字符 block 的数组?

转载 作者:行者123 更新时间:2023-12-02 18:45:07 25 4
gpt4 key购买 nike

例如,当给出“hello world”时,我希望返回[ "he", "ll", "o ", "wo", "rl", "d"]

我尝试过"hello world".split(/../g),但它不起作用,我只是得到空字符串:

console.log("hello world".split(/../g));

我还尝试使用捕获组,这使我更接近目标:

console.log("hello world".split(/(..)/g));

我在这里能想到的唯一真正的解决方案是用这样的东西删除空值:

let arr = "hello world".split(/(..)/g);

for (let i = 0; i < arr.length; i++) {
if (arr[i] === "") arr.splice(i, 1);
}

console.log(arr);

尽管这有效,但需要阅读的内容还有很多。有没有可能在 split 函数中做到这一点?

其他尝试的解决方案

let str = "hello world";
let arr = [];
for (let i = 0; i < str.length; i++) {
arr.push(str[i++] + (str[i] || ''));
}
console.log(arr);

最佳答案

您可以使用.match()将字符串拆分为两个字符:

var str = 'hello world';
console.log(str.match(/.{1,2}/g));

您还可以通过将 {1,2} 编辑为 34 等数字来增加拆分数量5 如示例所示:

拆分为 3 个字符:

var str = 'hello world';
console.log(str.match(/.{1,3}/g));

4 个字符分割:

var str = 'hello world';
console.log(str.match(/.{1,4}/g));

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

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