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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

Incredible Demos

  • By
    CSS Vertical Centering

    Front-end developing is beautiful, and it's getting prettier by the day. Nowadays we got so many concepts, methodologies, good practices and whatnot to make our work stand out from the rest. Javascript (along with its countless third party libraries) and CSS have grown so big, helping...

  • By
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

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!