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

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay