JavaScript, how to remove multiple line breaks

By

Learn how to remove multiple line breaks from a string in JavaScript with a single replace call and a regular expression that collapses them into one.

~~~

To remove multiple line breaks from a string in JavaScript, use replace() with a regular expression that matches runs of line break characters and collapses them.

I ran into this with a string that had too many line breaks between paragraphs, something like this:

A phrase...



Another phrase...


Another phrase...

But I wanted at most one blank line between the phrases:

A phrase...

Another phrase...

Another phrase...

Here’s what I did to get the result I wanted:

text = text.replace(/[\r\n]{2,}/g, '\n\n')

How the regular expression works

Let’s break it down.

[\r\n] is a character class that matches either \r (carriage return) or \n (line feed). Text coming from Windows uses \r\n for line endings, macOS and Linux use \n alone. The class covers both, so the code works no matter where the string came from.

{2,} means two or more of them in a row. A single line break is left alone.

The g flag applies the replacement to every match in the string, not just the first one.

The replacement is '\n\n', two newlines. So every run of two or more line break characters becomes exactly one blank line.

If you don’t want any blank lines at all, replace with a single '\n' instead:

text = text.replace(/[\r\n]{2,}/g, '\n')

Now the phrases sit on consecutive lines.

A pitfall: forgetting the g flag

Without the g flag, replace() only touches the first match:

'one\n\n\ntwo\n\n\nthree'.replace(/[\r\n]{2,}/, '\n\n')
// 'one\n\ntwo\n\n\nthree'

The line breaks between two and three are still there. It’s an easy bug to miss, because the string looks mostly fixed. Add the g flag and every occurrence gets collapsed.

If regular expressions are a mystery to you, check my regular expressions guide.

You can also paste the text into my text cleaner and choose how to handle spaces, blank lines, and line endings.

~~~

Related posts about js: