Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple line breaks (\n) in JavaScript

We have an onboarding form for new employees with multiple newlines (4-5 between lines) that need stripped. I want to get rid of the extra newlines but still space out the blocks with one \n.

example:

New employee<br/>
John Doe

Employee Number<br/>
1234

I'm currently using text = text.replace(/(\r\n|\r|\n)+/g, '$1'); but that gets rid of all newlines without spacing.

like image 222
user3512256 Avatar asked Apr 09 '14 12:04

user3512256


2 Answers

text = text.replace(/(\r\n|\r|\n){2,}/g, '$1\n');

use this, it will remove newlines where there are at least 2 or more

update

on specific requirement of the OP I will edit the answer a bit.

text = text.replace(/(\r\n|\r|\n){2}/g, '$1').replace(/(\r\n|\r|\n){3,}/g, '$1\n');
like image 173
aelor Avatar answered Nov 10 '22 21:11

aelor


We can tidy up the regex as follows:

text = text.replace(/[\r\n]{2,}/g, "\n");
like image 26
Greg Burghardt Avatar answered Nov 10 '22 19:11

Greg Burghardt