JSFiddle - React, Tailwind, and code Playground

JavaScript

var string = `
    foo



    bar (there are whitespaced lines between bar and baz)
                     
                    
                     
    baz
`;

// It works
//string = string.replace(/^(\s*\n){2,}/gm, '\n');

// Why it doesn't work?
var EOL = string.match(/\r\n/gm) ? '\r\n' : '\n';
var regExp = new RegExp('^(\s*' + EOL + '){2,}', 'gm');
string = string.replace(regExp, EOL);

alert(string);