Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a JavaScript string into fixed-length pieces

I would like to split a string into fixed-length (N, for example) pieces. Of course, last piece could be shorter, if original string's length is not multiple of N.

I need the fastest method to do it, but also the simplest to write. The way I have been doing it until now is the following:

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 must be a better way to do what I want. But I don't want extra modules or libraries, just simple JavaScript if it's possible.

Before ask, I have seen some solutions to resolve this problem using other languages, but they are not designed with JavaScript in mind.

like image 884
sgmonda Avatar asked May 06 '12 22:05

sgmonda


People also ask

Can we divide string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you cut a string in JavaScript?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.


2 Answers

You can try this:

var a = 'aaaabbbbccccee';
var b = a.match(/(.{1,4})/g);
like image 60
Danilo Valente Avatar answered Sep 22 '22 00:09

Danilo Valente


See this related question: https://stackoverflow.com/a/10456644/711085 and https://stackoverflow.com/a/8495740/711085 (See performance test in comments if performance is an issue.)

First (slower) link:

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

As a string prototype:

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

Demo:

> '123412341234123412'.chunk(4)
["1234", "1234", "1234", "1234", "12"]
like image 28
ninjagecko Avatar answered Sep 22 '22 00:09

ninjagecko