Javascript-only wordwrap function on whitespace?

javascript

Solution

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>

Problem

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.

Original source