Last active
January 24, 2020 17:40
-
-
Save westc/d9230bf447a551d2b21d2c595fcde46d to your computer and use it in GitHub Desktop.
Wrap text by splitting the lines based on whitespace and a maximum number of characters.
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
function wrapText(str, opt_max) { | |
opt_max = Math.min(Math.max(1, ~~opt_max || 80), 200); | |
let rgx = new RegExp(`\\S{1,${opt_max}}|\\s{1,${opt_max}}`, 'g'); | |
let lastPart, wasNotWS; | |
return (str.match(rgx) || []).reduce(function (lines, part, partIndex, parts) { | |
let isNotWS = /\S/.test(part); | |
if (isNotWS) { | |
let lineCount = lines.length; | |
let lastLine = lines[lineCount - 1]; | |
let newLastLine; | |
if (partIndex > 0 && (newLastLine = lastLine + (wasNotWS ? '' : lastPart) + part).length <= opt_max) { | |
lines[lineCount - 1] = newLastLine; | |
} | |
else { | |
lines[lineCount] = part; | |
} | |
} | |
lastPart = part; | |
wasNotWS = isNotWS; | |
return lines; | |
}, []).join('\r\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment