Word-Wrap in JavaScript
In rare cases, especially when you use the <pre>
tag, you may want to insert line breaks at the 80 character mark. Here’s some code to do that:
function wordWrap(text,boundary) {
return text.split("\n").map(function(line) {
var pos = 0;
return line.split(/\b/).map(function(word) {
pos += word.length;
if(pos > boundary) {
pos = 0;
return "\n" + word.trimLeft();
}
return word;
}).join("");
}).join("\n");
}