Created
September 9, 2017 09:33
-
-
Save IceCreamYou/a0ed4792dfd7ac3e375302fedfe31875 to your computer and use it in GitHub Desktop.
Implements simple character-count-based word wrapping with regular expressions in JavaScript
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
/** | |
* 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