How to Remove Multiple Line Breaks From a String with JavaScript

Want to limit line breaks to a single line?

Hello world

Hello from here...

Another hello! 👋

First let's look at what this would look like as a string:

"Hello world\n\n\nHello from here...\n\n\n\nAnother hello!  👋"

In a string, \n indicates a line break.

With a simple regular expression we can tidy this up so it looks like this rendered:

Hello world
Hello from here...
Another hello! 👋

Here's how

let str = "Hello world\n\n\nHello from here...\n\n\n\nAnother hello!👋";
str = str.replace(/\n\s*\n/g, '\n');
// Output: "Hello world\nHello from here...\nAnother hello!👋"

Why does this work?

The regular expression /\n\s*\n/g is used in this example. Here's what it does:

  • \n: Matches a newline character.
  • \s*: Matches zero or more whitespace characters. This includes spaces, tabs, and other forms of whitespace.
  • g: The global flag tells the replace method to replace all instances, not just the first one.

Using this regular expression, we tell the replace method to find all instances of two (or more) newline characters with any whitespace in between and replace them with a single newline character.

Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.