1

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?enter image description here

Fábio Zangirolami
  • 1,856
  • 4
  • 18
  • 33

2 Answers2

5

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
5

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 I.e a single line-break character supported by OS.
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179