Split large string in n-size chunks in JavaScript
I created several faster variants which you can see on jsPerf. My favorite one is this:
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
You can do something like this:
"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]
The method will still work with strings whose size is not an exact multiple of the chunk-size:
"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]
In general, for any string out of which you want to extract at-most n-sized substrings, you would do:
str.match(/.{1,n}/g); // Replace n with the size of the substring
If your string can contain newlines or carriage returns, you would do:
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
As far as performance, I tried this out with approximately 10k characters and it took a little over a second on Chrome. YMMV.
This can also be used in a reusable function:
function chunkString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g'));
}
- comparison of
match
,slice
,substr
andsubstring
- comparison of
match
andslice
for different chunk sizes - comparison of
match
andslice
with small chunk size
Bottom line:
match
is very inefficient,slice
is better, on Firefoxsubstr
/substring
is better stillmatch
is even more inefficient for short strings (even with cached regex - probably due to regex parsing setup time)match
is even more inefficient for large chunk size (probably due to inability to "jump")- for longer strings with very small chunk size,
match
outperformsslice
on older IE but still loses on all other systems - jsperf rocks