How do I replace multiple \n
's with just one? So if a user enters
blah
blahdy blah
blah blah
I want it to end up looking like.
blah
blahdy blah
blah blah
I know I could loop through with a while() but would rather use a regular expression, since I believe it's more efficient.
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.
Simply use a character class to replace one or more \n
or \r
with a single \n
:
var newString = oldString.replace(/[\n\r]+/g, "\n");
Test HTML:
<script>
function process(id) {
var oldString = document.getElementById(id).value;
var newString = oldString.replace(/[\n\r]+/g, "\n");
return newString;
}
</script>
<textarea id="test"></textarea>
<button onclick="alert(process('test'));">Test</button>
Please note: In the modern web, and in most modern applications, a single \n
line ending is handled gracefully, which is why I've used that as my replacement string here. However, some more primitive applications on CR+LF (\r\n
) operating systems will display all text run together without the full \r\n
, in which case you could use Dan Tao's answer, which provides a solution to preserve line endings, or the following, which accomplishes a similar thing in one call:
string.replace(/(\r\n|\r|\n)+/g, "$1");
var blah = "blah\n\nblahdy blah\n\n\n\nblah blah\n";
var squeezed = blah.replace(/\n+/g, "\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With