开发者

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.


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");


You can use regex

xx.replace(/\n+/g, "\n");


Or without the overhead of the JavaScript engine setting up a finite state machine to run the regular expression, you can do it with arrays:

s = s.split("\n").join("");


Doing the same for spaces with detailed examples: Regex to replace multiple spaces with a single space. Example:

var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜