如何在 Javascript 中以特定间隔将字符串拆分为数组

How to split strings at specific intervals to arrays in Javascript

本文关键字:字符串 拆分 数组 Javascript      更新时间:2023-09-26

如何在Javascript中以特定的间隔将字符串拆分为数组?

例如:将此字符串拆分为 4 个字符(包括空格和字符)

this is an example should be split,numbers(123),space,characters also included

this ------> 1st array
 is  ------> 2nd array
 an  ------> 3rd array
exam ------> 4th array
ple  ------> 5th array
shou ------> 6th array     ............ etc till.....
..ed ------> last array

试试这个:

    var foo = "this is an example should be split,numbers(123),space,characters also included"; 
    var arr = [];
    for (var i = 0; i < foo.length; i++) {
        if (i % 4 == 0 && i != 0)
            arr.push(foo.substring(i - 4, i));
        if (i == foo.length - 1)
            arr.push(foo.substring(i - (i % 4), i+1));          
    }
    document.write(arr);
    console.log(arr);

下面是一个函数,可以将字符串拆分为所需大小的块:

function splitN(s, n) {
    var output = [];
    for (var i = 0; i < s.length; i+=4) {
        output.push(s.substr(i, 4));
    }
    return(output);
}

你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/JvabJ/

将上面代码中的"4"更改为"n":

function splitN(s, n) {
    var output = [];
    for (var i = 0; i < s.length; i+=n) {
        output.push(s.substr(i, n));
    }
    return(output);
}

您可以将match与正则表达式一起使用:

console.log("this is an example should be split,numbers(123),space,characters also included".match(/.{1,4}/g));