MNS
MNS

Reputation: 395

Remove one newline?

I am using body.replace(/\r?\n((?!\r?\n)|(?=\r?\n\r?\n\r?\n))/g,''), to replace newlines, the problem is it removes them all, in case there are two or more newlines one after another i want to keep them since it represent a paragraph.

for example :

Money causes teenagers to feel stress.
It makes them feel bad about themselves and envy other people.
My friend, for instance, lives with her family and has to share a room with her sister,
who is very cute and intelligent.

This girl wishes she could have her own room and have a lot of stuff,
but she can’t have these things because her family doesn’t have much money.
Her family’s income is pretty low because her father is old and doesn’t go to work.

I want it to be like :

Money causes teenagers to feel stress. It makes them feel bad about themselves and envy other people. My friend, for instance, lives with her family and has to share a room with her sister, who is very cute and intelligent.

This girl wishes she could have her own room and have a lot of stuff, but she can’t have these things because her family doesn’t have much money. Her family’s income is pretty low because her father is old and doesn’t go to work.

Thanks in advance.

Upvotes: 1

Views: 121

Answers (2)

Anirudha
Anirudha

Reputation: 32787

You could do this

body.replace(/([^\n])(?:\r?\n)(?=[^\n])/g,"$1");

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213213

You don't need such a complex regex. Those look-arounds are really not needed.

You can simply use this:

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

$1 is back-reference. Replace it with \1 if it is used in your regex engine.

Upvotes: 3

Related Questions