javascript 你可以让换行符 \n 显示为换行符 <br /> 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13118738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:50:55  来源:igfitidea点击:

Can you make newline characters \n display as breaks <br />?

javascripthtmlcssformatting

提问by James

I'm trying to display emails with IMAP. When the email is text though, the newlines \n don't display properly. I'd rather not convert them to breaks < br /> because if the user wanted to reply to that email, it would now be in HTML instead of plain text. Is there perhaps a javascript function that could display it as a line break without changing the code?

我正在尝试使用 IMAP 显示电子邮件。但是,当电子邮件是文本时,换行符 \n 无法正确显示。我宁愿不将它们转换为中断 <br /> 因为如果用户想回复该电子邮件,它现在将使用 HTML 而不是纯文本。是否有一个 javascript 函数可以在不更改代码的情况下将其显示为换行符?

回答by Vilx-

How about HTML/CSS? If you put your text inside a <pre>tag, it will show all newlines exactly as they were. Alternatively, you can achieve the same effect by applying the CSS style white-space:preto any element.

HTML/CSS 怎么样?如果您将文本放在<pre>标签中,它将完全按原样显示所有换行符。或者,您可以通过将 CSS 样式white-space:pre应用于任何元素来实现相同的效果。

Don't forget to HTMLencode it still (<to &lt;etc.), otherwise it will all break apart at the first angle bracket.

不要忘记对它进行 HTMLencode(<to&lt;等),否则它会在第一个尖括号处分开。

回答by Chtiwi Malek

Just add this white-spacecss style property to render Multiline texts :

只需添加此white-spacecss 样式属性即可呈现多行文本:

.multiline
{
   white-space: pre-wrap;
}

and then :

接着 :

<div class="multiline">
  my
  multiline
  text
</div>

now newlineswill render like br elements.

现在换行符将呈现为 br 元素。

回答by kesh

white-space CSS works fine but for cross-browser compatibility

空白 CSS 工作正常,但为了跨浏览器兼容性

.abc {
  word-wrap: break-word;      /* IE 5.5-7 */
  white-space: pre-wrap;      /* Modern browsers */
}

Your Html

你的 HTML

<div class="abc">
 Lorem 
 Ipsum 
 is 
 simply 
 dummy
</div>

MDN Source

MDN 来源