1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Breaking Text into Chunks

While JavaScript contains a whole range of methods for manipulating text there will be occasions where you want to do something with your text that doesn't appear (at least initially) to be so easy to do. One such example would be to be able to take a string of text and break it up into pieces that are all the same length so that we can access each of those pieces separately. For example let's say we have text that is 30 characters long and we want to break it into five strings of six characters each.

Perhaps you would look at creating some complex piece of JavaScript to do this for you. In fact all we need to do it is one line of code using a simple but not necessarily obvious regular expression. We can even cater for the string not being able to be divided evenly and return any leftover characters (as would be the case if our string were 28 or 33 characters long and we were splitting it into six character chunks).

Another simple modification to the code and we can set up a function (or better yet a new String method) that allows you to pass the size of the chunks you want the text broken into. Of course if we are going to do that then we really ought to also define a default size for the chunks in case we call the method and forget to tell it a size.

So how much code do we need to do all this? Not very much at all as you can see.

String.prototype.chunk = function(n) {
if (typeof n=='undefined') n=2;
return this.match(RegExp('.{1,'+n+'}','g'));

Adding this code into your JavaScript allows you to convert any text string into an array with each chunk (except possibly the last) being the specified size (or 2 characters if you don't specify a size). Here's an example:

var s = 'abcdefghijklmnopqrstuvwxyz1234';
var a = s.chunk(6);

This gives us our array with five elements each containing six characters from the string and is equivalent to specifying:

var a = ['abcdef','ghijkl','mnopqr','stuvwx','yz1234'];

Of course if we wanted it broken into 15 chunks of two characters each we just need to remove the 6 from the second line and call s.chunk() and since 2 is the default size it will use that as the size for the chunks since we have not specified a different size. With the 6 removed our code is now equicalent to:

var a = ['ab','cd','ef','gh','ij','kl','mn','op','qr','st','uv','wx','yz','12','34'];
See More About
Related Video
Wrap Text Effect in Photoshop
Formatting HTML text

©2017 About.com. All rights reserved.