Created
August 8, 2015 22:07
-
-
Save JavaScript-Packer/35ca565c9e5fe8fa1ff9 to your computer and use it in GitHub Desktop.
Wrap words to line length approximate so we do not break words. Function from http://www.whak.com/javascript-packer.htm
This file contains hidden or 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
function wordWrap(str, width, prefix, postfix) { | |
var p, left, right; | |
if (str.length > width) { | |
p = width; | |
for (;p > 0 && !/\s/.test(str[p]); p--) ; | |
if (p > 0) { | |
left = str.substring(0, p); | |
right = str.substring(p + 1); | |
return prefix + left + postfix + wordWrap(right, width, prefix, postfix); | |
} | |
} | |
return str; | |
} | |
/* | |
// SAMPLE USAGES: | |
var str = "www.WHAK.com has to take a long string of text and break it into rows (word wrap, we do not want to break up words) of maximum 40 chars. Some things like News Groups require each line be less than a cetain amount of characters. Would be nice if I could add some default text before and after each line too!"; | |
wrapper.innerHTML = wordWrap(str, 40, "<p>", "</p>"); | |
alert(wordWrap(str, 40, "\n", "")); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will take a long string
of text and break it into rows (word
wrap, we do not want to break up words)
of maximum 40 chars. Some things like
News Groups require each line be less
than a certain amount of characters.
Would be nice if I could add some
default text before and after each line
too! That would rock!
SOURCE CODE: