0

特定の間隔で文字列を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
4

2 に答える 2

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);
于 2012-07-07T07:28:03.857 に答える