Anthony Fu @ antfu.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|$)/).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 mastodon / twitter
>
CC BY-NC-SA 4.0 2021-PRESENT © Anthony Fu