Good day,
I would like to know if there is an easy way to chunk/split a string without breaking the words.
Eg:
var input = \"Lorem ipsum dolo
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/