Divide the JavaScript string into fixed-length shapes.

I would like to split a string into parts with a fixed length (N, for example). Of course, the last piece can be shorter if the original string length is not a multiple of N.

I need the fastest way to do this, but also the easiest to write. So far I have done it like this:

var a = 'aaaabbbbccccee';
var b = [];
for(var i = 4; i < a.length; i += 4){ // length 4, for example
    b.push(a.slice(i-4, i));
}
b.push(a.slice(a.length - (4 - a.length % 4))); // last fragment

I think there should be a better way to do what I want. But I do not want additional modules or libraries, just JavaScript, if possible.

Before asking, I saw some solutions to solve this problem using other languages, but they are not designed with JavaScript in mind.

+5
source share
2 answers

You can try the following:

var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);
+17
source

: fooobar.com/questions/27184/... fooobar.com/questions/27184/... (. , .)

( ) :

[].concat.apply([],
    a.split('').map(function(x,i){ return i%4 ? [] : a.slice(i,i+4) })
)

:

String.prototype.chunk = function(size) {
    return [].concat.apply([],
        this.split('').map(function(x,i){ return i%size ? [] : this.slice(i,i+size) }, this)
    )
}

:

> '123412341234123412'.chunk(4)
["1234", "1234", "1234", "1234", "12"]
+4

All Articles