I was working on a project recently where I recieved a data feed and needed to split it into sections that would fit into a text box (ie. 200 characters at a time). The user would then click ‘more‘ and progress through the text in segments until they had read all of it.

I wrote this simple prototype, which splits a string into sections of a defined size (and optionally adds a postfix, ie. “…” to the end), and returns an array containing the segmented text.

Here is the prototype:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
String.prototype.splitUp = function (maxLetters, postFix)
{
	var txt:String = this + 1;
	var split:Array = new Array ();
 
	var num = 0;
	var counter = 0;
	while (num >= 0)
	{
		var num = txt.indexOf (" ", maxLetters);
 
		if (postFix != undefined && num >= 0)
		{
			var t = txt.slice (0, num) + postFix;
		}
		else
		{
			var t = txt.slice (0, num);
		}
 
		split[counter] = t;
		txt = txt.slice (num + 1, txt.length);
		counter++;
	}
 
	return split;
};

… And an example of it’s usage - in this instance the string is converted to an array which can then be used to populate a text box:

var phrases = blurb.splitUp (190, "...");

It may have some bugs as I have only tested it within the context of the project I wrote it for. With a little added Actionscript though, it should be a useful tool.