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

I have the following text sent by the user with breaklinesText of example in line 1.(break line)(brea

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

  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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745199184a4616241.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信