Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty lines between lines with content

I'd like to know if someone can help me with regex on javascript.

So basically I have the following string as an example:

var str = "A\nB\n\n\nC\n\n\n\n\nD" and I want to convert it to "A\nB\n\nC\n\n\n\nD" using regex or any other way around to do this with javascript.

The idea here is remove only one empty line between lines with content. Is there any way to do this?

like image 732
Pedro Nascimento Avatar asked Sep 13 '26 01:09

Pedro Nascimento


1 Answers

One possible approach:

var str = "A\nB\n\n\nC\n\n\n\n\nD"

var out = str.replace(/\n(\n+)/g, '$1')

console.log(out) // "A\nB\n\nC\n\n\n\nD"
like image 60
TimoStaudinger Avatar answered Sep 14 '26 14:09

TimoStaudinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!