chunk/split a string in Javascript without breaking words
Here's some brute force code that will do it:
function splitIntoLines(input, len) {
var i;
var output = [];
var lineSoFar = "";
var temp;
var words = input.split(' ');
for (i = 0; i < words.length;) {
// check if adding this word would exceed the len
temp = addWordOntoLine(lineSoFar, words[i]);
if (temp.length > len) {
if (lineSoFar.length == 0) {
lineSoFar = temp; // force to put at least one word in each line
i++; // skip past this word now
}
output.push(lineSoFar); // put line into output
lineSoFar = ""; // init back to empty
} else {
lineSoFar = temp; // take the new word
i++; // skip past this word now
}
}
if (lineSoFar.length > 0) {
output.push(lineSoFar);
}
return(output);
}
function addWordOntoLine(line, word) {
if (line.length != 0) {
line += " ";
}
return(line += word);
}
If this routine encounters a single word longer than the desired line length, it will put it on a line by itself and will not break it up.
You can play with it here: http://jsfiddle.net/jfriend00/fbaLe/
This builds on @steve's answer but will split the string respecting word break so that the string is never longer than the specified length. This works more like a normal word wrap.
function chunkString(s, len)
{
var curr = len, prev = 0;
output = [];
while(s[curr]) {
if(s[curr++] == ' ') {
output.push(s.substring(prev,curr));
prev = curr;
curr += len;
}
else
{
var currReverse = curr;
do {
if(s.substring(currReverse - 1, currReverse) == ' ')
{
output.push(s.substring(prev,currReverse));
prev = currReverse;
curr = currReverse + len;
break;
}
currReverse--;
} while(currReverse > prev)
}
}
output.push(s.substr(prev));
return output;
}