简体   繁体   中英

Remove all line-breaks, but except only one break?

I have the following text sent by the user with breaklines

Text of example in line 1.
(break line)
(break line)
(break line)
The text is very nice...
(break line)
(break line)
The end.

Result expected:

Text of example in line 1.
The text is very nice...
The end.

NOT: Text of example in line 1. The text is very nice... The end.

How I do this in JavaScript( str.replace ) receiving via AJAX in PHP

$text = strip_tags($text, '<br>');

Thank you for answers! But I tested all .. and then I went to see that my DIV is generating HTML codes, I believe that is why it is not working (RegEx). How do I ignore HTML elements to be able to text with line breaks? 在此处输入图片说明

You can use a regex replace.

str = str.replace(/\n{2,}/g, "\n");

{2,} means to match 2 or more of the previous expression. So any sequence of 2 or more newlines will be replaced with a single newline.

Although, the answer by @Barmar is correct, it'll not work across different OS/platforms.

Different OS uses different character combination to use as linebreak.

  1. Windows: \\r\\n = CR LF
  2. Unix/Linux: \\n = LF
  3. Mac: \\r = CR

See \\r\\n , \\r , \\n what is the difference between them?

I'll suggest the following RegEx that will work across platforms.

str = str.replace(/(\r\n?|\n){2,}/g, '$1');

Live RegEx Demo

Explanation:

  1. () : Capturing group
  2. \\r\\n? : Matches \\r followed by \\n optionally. Thus matches
    • \\r\\n OR
    • \\r
  3. | : OR condition in RegEx
  4. \\n : Match \\n
  5. {2,} : Match previous character/s two or more times
  6. g : Global flag
  7. $1 : The first captured group Ie a single line-break character supported by OS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM