最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.
发布评论

评论列表(0)

  1. 暂无评论