Skip to content

Instantly share code, notes, and snippets.

@westc
Last active January 24, 2020 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save westc/d9230bf447a551d2b21d2c595fcde46d to your computer and use it in GitHub Desktop.
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.
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