Most wordwrap functions I've found are bound to css and/or a browser dom. I'm working in a javascript environment (rhino) and need to find or design a better word wrap that breaks on whitespace before a given line length value. My current solution just searches for the last white space before the given character, then clips the left side, storing it as a line of output (in an array return). Repeat until no more text remains.
Hoping someone has seen something elegant.
You could write something like:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
That will replace \s+
with \n
after at-least-one,-at-most-eighty,-preferably-as-many-as-possible characters. (Note: if there are more than eighty characters in a row without whitespace, then there will be a line-break before and after them, but no wrapping will take place inside them.)
See it in action:
// generate random sequence of 500 letters and spaces:
let original = String.fromCharCode.apply(String, Array.from({length: 500}, () => 64 + Math.floor(Math.random() * 27))).replace(/@/g, ' ');
// perform word-wrapping:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
// show the results in the <pre> elements:
document.getElementById('ruakh-original').innerText = 'original:\n' + original;
document.getElementById('ruakh-word-wrapped').innerText = 'word-wrapped:\n' + wordwrapped;
<pre id="ruakh-original"></pre>
<pre id="ruakh-word-wrapped"></pre>
This regex will wrap every 0-width character and respect whitespaces and hyphens also cuts words longer than width characters. Try it out on regexr.
/**
* Wrap every 0-`width` character and respect whitespaces and hyphens also cuts words longer than `width` characters.
* @param str The string to wrapped
* @param width The maximum length a string can be
*/
function wordwrap(str, width) {
return str.replace(new RegExp(`(?:\\S(?:.{0,${width}}\\S)?(?:\\s+|-|$)|(?:\\S{${width}}))`, 'g'), s => `${s}\n`).slice(0, -1);
}
function wordwrap(str, width) {
return str.replace(new RegExp('(?:\\S(?:.{0,' + width + '}\\S)?(?:\\s+|-|$)|(?:\\S{' + width + '}))', 'g'), function (s) {return s + '\n'}).slice(0, -1);
}
console.log(wordwrap('This is my regular-expression. It will wrap every 0-20 character and respect whitespaces and hyphens, also cuts reallylongwordslikethis.', 20));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With