This worked for me:
string = string.replace(/\n+/g, '\n');
As others have said, it replaces each occurrence of one or more consecutive newline characters (\n+
) with just one.
The g
effects a "global" replace, meaning it replaces all matches in the string rather than just the first one.
Edit: If you want to take into account other operating systems' line ending styles as well (e.g., \r\n
), you could do a multi-step replace:
string = string.replace(/(\r\n)+/g, '\r\n') // for Windows
.replace(/\r+/g, '\r') // for Mac OS 9 and prior
.replace(/\n+/g, '\n'); // for everything else
OR (thanks to Renesis for this idea):
string = string.replace(/(\r\n|\r|\n)+/g, '$1');
If you know in advance what sort of text you're dealing with, the above is probably overkill as it carries am obvious performance cost.