Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Created September 9, 2017 09:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IceCreamYou/a0ed4792dfd7ac3e375302fedfe31875 to your computer and use it in GitHub Desktop.
Save IceCreamYou/a0ed4792dfd7ac3e375302fedfe31875 to your computer and use it in GitHub Desktop.
Implements simple character-count-based word wrapping with regular expressions in JavaScript
/**
* Wraps the specified string onto multiple lines by character count.
*
* Words (consecutive non-space characters) are not split up.
* Lines may be shorter than `len` characters as a result.
* Careful: words longer than `len` will be dropped!
*
* @param str The string to wrap.
* @param len The max character count per line.
*
* @returns A newline-delimited string.
*/
function wordwrap(str, len) {
return (
str.match(
new RegExp('(\\S.{0,' + (len-1) + '})(?=\\s+|$)', 'g')
) || []
).join('\n');
}
// Example usage:
wordwrap('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.', 25)
// Produces this string:
// The quick brown fox jumps
// over the lazy dog. The
// quick brown fox jumps
// over the lazy dog.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment