Created
June 10, 2012 08:59
-
-
Save nfeldman/2904580 to your computer and use it in GitHub Desktop.
break text into lines of length n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a bit messy and not optimized, but handy for basic formatting of short blocks of text | |
function splitToLines (string, leftMarginWidth, maxLineWidth) { | |
var lines = [], | |
line = [], | |
padding = Array(leftMarginWidth).join(' '), | |
i = 0, // cursor | |
p = 0, // left anchor | |
m = 0, // counter for searching 5 char wrap zone | |
s, // tmpvar | |
l = string.length, | |
mLen = maxLineWidth - leftMarginWidth - 5; | |
while (l > i) { | |
i && line.push(padding); | |
!i && (i = maxLineWidth - 5); | |
while (i-- > p) { | |
s = string.charAt(i); | |
if (s == ' ' || s == '-') { | |
i++; | |
break; | |
} | |
} | |
if (i == p) { | |
i += mLen; | |
while (string.charAt(i++) != ' ' && 5 > m++); | |
if (string.charAt(i) != ' ') | |
break; | |
else | |
m = 0; | |
} | |
line.push(string.slice(p, i)); | |
lines.push(line.join('')); | |
line.length = 0; | |
p = i; | |
i += mLen; | |
} | |
lines.push(padding + string.slice(p)); | |
return lines.join('\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example:
should result in: