Skip to content
Advertisement

Split large string in n-size chunks in JavaScript

I would like to split a very large string (let’s say, 10,000 characters) into N-size chunks.

What would be the best way in terms of performance to do this?

For instance: "1234567890" split by 2 would become ["12", "34", "56", "78", "90"].

Would something like this be possible using String.prototype.match and if so, would that be the best way to do it in terms of performance?

Advertisement

Answer

You can do something like this:

JavaScript

The method will still work with strings whose size is not an exact multiple of the chunk-size:

JavaScript

In general, for any string out of which you want to extract at-most n-sized substrings, you would do:

JavaScript

If your string can contain newlines or carriage returns, you would do:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement