Remove Multiple New Lines with JavaScript

By  on  

I'm blessed in that lots of people want to guest post on this blog.  It's really flattering and I love seeing writers get a bunch of attention after writing.  My task is converting the blog post, in whatever format it's provided in (HTML, Markdown, PDF, Google Doc, etc.), to HTML for my blog, which can sometimes get messy.  I employ a host of regular expressions to fix these formatting issues.  And the number one problem?  Loads of extra new lines (\n).

The Regular Expression

The regular expression is actually quite simple:

content.replace(/[\r\n]+/g, '\n'); // Just one new line

content.replace(/[\r\n]+/g, '\n\n'); // "document" formatting, more elegant

With the dozens of extra lines gone it's much easier to work with the content!

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Optimize Your Links For Print Using CSS — Show The URL

    When moving around from page to page in your trusty browser, you get the benefit of hovering over links and viewing the link's target URL in the status bar. When it comes to page printouts, however, this obviously isn't an option. Most website printouts...

Discussion

  1. Adam van den Hoven

    David,

    I’m more inclined to use something like:

    content.replace(/[\r\n]\s*/g, '\n'); // Just one new line
    content.replace(/[\r\n]\s*/g, '\n\n'); // "document" formatting, more elegant
    

    Only there always seems to be some extra whitespace between those newlines. If you don’t want to loose the tabs on the next line then this works just as well

    content.replace(/[\r\n]\s*[\r\n]/g, '\n'); // Just one new line
    content.replace(/[\r\n]\s*[\r\n]/g, '\n\n'); // "document" formatting, more elegant
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!