Skip to content

Instantly share code, notes, and snippets.

@JavaScript-Packer
Created August 8, 2015 22:07
Show Gist options
  • Save JavaScript-Packer/35ca565c9e5fe8fa1ff9 to your computer and use it in GitHub Desktop.
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
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", ""));
*/
@JavaScript-Packer
Copy link
Author

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:

<div id="wrapper"></div>
<script>
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!"
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;
}

wrapper.innerHTML = wordWrap(str, 40, "<p>", "</p>");

alert(wordWrap(str, 40, "\n", ""));
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment