Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple \n with 1 in JavaScript

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.

like image 931
mazlix Avatar asked Jul 13 '11 22:07

mazlix


3 Answers

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.

like image 117
Dan Tao Avatar answered Nov 12 '22 17:11

Dan Tao


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");
like image 43
Nicole Avatar answered Nov 12 '22 17:11

Nicole


var blah = "blah\n\nblahdy blah\n\n\n\nblah blah\n";
var squeezed = blah.replace(/\n+/g, "\n");
like image 3
MarkD Avatar answered Nov 12 '22 17:11

MarkD