DEV Community

Justin
Justin

Posted on • Edited 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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series