Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple blank lines in text using Javascript

Hopefully a simple question.

If I have text like this:

Orange
Apples


Melons

Bananas

...how can I replace all occurrences of multiple blank lines with single blank lines, ending up with this:

Orange
Apples

Melons

Bananas

Fiddle: http://jsfiddle.net/Jq4pT/ Need to remove multiple blank lines from the first box's input before inserting into the second.

I've found this link, but am not sure how to use that regular expression in Javascript?

Thanks.

like image 880
Fijjit Avatar asked Feb 05 '26 23:02

Fijjit


2 Answers

This is an old question, but I don't care, it comes up first in Google search.

You can do this with the following code:

var EOL = string.match(/\r\n/gm)?"\r\n":"\n";
var regExp = new RegExp("("+EOL+"){3,}", "gm");
string = string.replace(regExp, EOL+EOL);
  • First it determines the endline char to use in Regex
  • Regex looks for EOL chars being repeated 3 or more times, and replaces them with 2 EOL chars.
  • Using g modifier to replace all occurrences
  • Using m modifier to apply regex to the whole multi-line string, instead of per line.
like image 125
Cipi Avatar answered Feb 07 '26 12:02

Cipi


Just use it like this:

var inputString = '...';
var outputString = inputString.replace(/^(\s*\r\n){2,}/, "\r\n")
like image 25
Maksim Gladkov Avatar answered Feb 07 '26 11:02

Maksim Gladkov



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!