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?
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?
Share Improve this question edited Feb 27, 2016 at 15:47 Fábio Zangirolami asked Feb 26, 2016 at 23:41 Fábio ZangirolamiFábio Zangirolami 1,9664 gold badges19 silver badges33 bronze badges2 Answers
Reset to default 5You 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 bination to use as linebreak.
- Windows:
\r\n
= CR LF - Unix/Linux:
\n
= LF - 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:
()
: Capturing group\r\n?
: Matches\r
followed by\n
optionally. Thus matches\r\n
OR\r
|
: OR condition in RegEx\n
: Match\n
{2,}
: Match previous character/s two or more timesg
: Global flag$1
: The first captured group I.e a single line-break character supported by OS.