DEV Community

Justin
Justin

Posted on • Updated on

JS Challenge: Fold a long line of text into lines of 80ish characters without breaking words

The challenge is to wrap text after every 80th character. If the 80th character is within a word, wrap after the word ends.

Solution:

const longLine = `This is a long line of text that needs to be \
folded after 80ish characters. If the 80th character \
happens to be within a word, wrap the line after the word`;

console.log(longLine.replace(/([^\n\r]{80})\s+/g, "$1\n"));
Enter fullscreen mode Exit fullscreen mode

Basically the above code scans the long line of text for stretches of 80 characters without a line break followed by space(s) and inserts line breaks at those offsets.

If the 80th character falls within a word, the above code will forward to the end of that word and break there. But what if you don't want the lines to exceed 80 characters under no circumstances? In that case you need to go back to the end of the previous word and insert a line break there. The code below does exactly that:

const longLine = `This is a long line that needs to be folded \ 
into lines not more than 80 characters long without breaking \
words.`;

console.log(longLine.replace(/([^\n\r]{80}\s+)/g, 
  (m,g) => g.replace(/\s+([^\s]+\s*)$/, "\n$1")
));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)