13

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.

Gerben Jacobs
  • 4,515
  • 3
  • 34
  • 56
user3512256
  • 133
  • 1
  • 1
  • 4

2 Answers2

33
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');
aelor
  • 10,892
  • 3
  • 32
  • 48
  • If I understand the requirements correctly, that's not what's wanted: http://regex101.com/r/dA1tP5 – Scott Sauyet Apr 09 '14 at 12:27
  • Oh yes, that works, and it's much simpler than mine... http://regex101.com/r/jC5aI4 – Scott Sauyet Apr 09 '14 at 12:31
  • Thanks. The problem is there are single newlines between "New Employee" and "John Doe" then there are several newlines until the next value. It's all random. So I want to preserve one line break and get rid of any 2+ line breaks. http://regex101.com/r/zC8pS7 – user3512256 Apr 09 '14 at 13:01
  • aint you getting the expected result ? – aelor Apr 09 '14 at 13:03
  • you can ofcourse fiddle with the numbers in the last quatifier `{2,}` to get your expected o/p. try changing it to 1 or 3 and see what happens, I just want to help you to learn a bit here :) – aelor Apr 09 '14 at 13:05
  • So basically I want "If 2 /n replace with 1" then "If 3+ /n replace with 2" Sorry I wasn't more specific in the original question – user3512256 Apr 09 '14 at 13:07
17

We can tidy up the regex as follows:

text = text.replace(/[\r\n]{2,}/g, "\n");
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92