Search code examples
javascriptreplaceall

Javascript replace double carriage returns with single carriage returns


just trying to replace double carriage returns with single carriage returns in Javascript. Here are the details:

I've searched Google and Stack Overflow for this problem, and I've found a bunch of examples of replacing one string with another, but not double carriage returns with single carriage returns (essentially eliminating blank lines from a string). I figure there might be some weirdness with this case.

Here's an example of what I need:

Replace:

Line 1
Line 2


Line 3

Line 4

with:

Line 1
Line 2
Line 3
Line 4

I've tried the following lines of code (individually, not all at once):

stringReplace = stringReplace.replace(/\n\n/g, '\n');
stringReplace = stringReplace.replaceAll(/\n\n/g, '\n');
stringReplace = stringReplace.split('\n\n').join('\n');

An example of what I input is this (four blank lines in a row):

Line 1
Line 2




Line 3
Line 4

which turns into (still two blank lines in a row):

Line 1
Line 2


Line 3
Line 4

But I tried to replace the double carriage return with something entirely different, in this case a double equal sign:

stringReplace = stringReplace.replace(/\n\n/g, '==');

I enter:

Line 1




Line 2




Line 3


Line 4

Guess what? Works as planned.

Line 1===
Line 2====
Line 3==
Line 4

Any ideas what's going wrong, anyone? Thanks, everyone!


Solution

  • You should match two or more newlines (not just two, but two or more), and replace with a single newline:

    const input = `Line 1
    Line 2
    
    
    
    
    Line 3
    Line 4`;
    
    const output = input.replace(/\n{2,}/g, '\n');
    console.log(output);

    Another way of writing it: \n\n+ instead of \n{2,} (both patterns match two or more newlines)