Jarvis @ JM.me

Break Lines in JS

Feb 10, 2023 · 2min

You probably don’t need it usually, but in case you want to break lines programmatically in JavaScript, here is my lazy man’s solution:

// break lines at space with maximum 25 characters per line
text.split(/(.{0,25})(?:\s|$)/g).filter(Boolean)

A quick example:

const text = 'A quick brown fox jumps over the lazy dog.'
const lines = text.split(/(.{0,16})(?:\s|$)/g).filter(Boolean)

console.log(lines)
// ['A quick brown', 'fox jumps over', 'the lazy dog.']

You probably see a few edge cases already. But come on, it’s just one line of code :P

> Comment on twitter (X)
 
CC BY-NC-SA 4.0  2009-PRESENT © Nuxsco (AMS) This website rewrite several times from those years up to present