Check words into lines
by jfriend00
HTML
<div id="result"></div>
CSS
#result {white-space: nowrap}
.n {color: #f00;}
JavaScript
var input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat, nisi nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 sit amet, consectetur adipiscing elit.";
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);
}
var result = splitIntoLines(input, 80);
var str = "";
for (var i = 0; i < result.length; i++) {
str += "<span class='n'>" + (i + 1) + " - (" + result[i].length +"): </span>" + result[i] + "<br>";
}
$("#result").html(str + "</pre>");