简体   繁体   English

删除所有换行符,但只删除一个换行符?

[英]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. 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 我如何在通过PHP的AJAX接收的JavaScript( str.replace )中做到这一点

$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). 但是我测试了所有..然后我发现我的DIV正在生成HTML代码,我相信这就是为什么它不起作用(RegEx)。 How do I ignore HTML elements to be able to text with line breaks? 如何忽略HTML元素以使文本带有换行符? 在此处输入图片说明

You can use a regex replace. 您可以使用正则表达式替换。

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

{2,} means to match 2 or more of the previous expression. {2,}表示匹配前一个表达式的2个或多个。 So any sequence of 2 or more newlines will be replaced with a single newline. 因此,包含2个或更多换行符的任何序列都将替换为一个换行符。

Although, the answer by @Barmar is correct, it'll not work across different OS/platforms. 尽管@Barmar答案是正确的,但它不适用于不同的OS /平台。

Different OS uses different character combination to use as linebreak. 不同的OS使用不同的字符组合用作换行符。

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

See \\r\\n , \\r , \\n what is the difference between them? 参见\\ r \\ n,\\ r,\\ n它们之间有什么区别?

I'll suggest the following RegEx that will work across platforms. 我将建议以下可在各个平台上运行的RegEx。

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

Live RegEx Demo Live RegEx演示

Explanation: 说明:

  1. () : Capturing group () :捕获组
  2. \\r\\n? : Matches \\r followed by \\n optionally. :匹配\\r后跟\\n可选)。 Thus matches 因此匹配
    • \\r\\n OR \\r\\n
    • \\r
  3. | : OR condition in RegEx :RegEx中的OR条件
  4. \\n : Match \\n \\n :匹配\\n
  5. {2,} : Match previous character/s two or more times {2,} :匹配先前的字符两次或更多次
  6. g : Global flag g :全局标志
  7. $1 : The first captured group Ie a single line-break character supported by OS. $1 :第一个捕获的组,即OS支持的单个换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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