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

时间:2012-07-07 07:19:54

标签: javascript-events split

如何在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

2 个答案:

答案 0 :(得分:1)

试试这个:

    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);

答案 1 :(得分:1)

这是一个将您的字符串拆分成任意大小的块的函数:

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/