我有一个应用程序,从REST API接收评论字符串如下:
"comments":"This is a comment\nAnother comment\nOne more\nLast
我使用p标签展示文本,但是它不能识别换行符(\n)。如何实现换行?
我有一个应用程序,从REST API接收评论字符串如下:
"comments":"This is a comment\nAnother comment\nOne more\nLast
我使用p标签展示文本,但是它不能识别换行符(\n)。如何实现换行?
这可能与CSS有关,
如果你使用white-space: pre-wrap
,它可以确保识别换行符。
查看文档获取其他white-space
选项及其功能。
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
const nodes = document.getElementsByTagName('p');
// Replacing the innerHtml because the newline chars aren't acknowledged if I define them in the HTML.
for(let n of nodes) {
n.innerHTML = 'Here is \nSome example \nText with \nLine breaks.'
}
p.no-breaks {
white-space: nowrap;
color: red;
}
p.with-breaks {
white-space: pre-wrap;
color: blue;
}
<p class="no-breaks">This text will be replaced.</p>
<p class="with-breaks">This text will be replaced.</p>
<pre>
标签是设置识别换行符的。您可以通过CSS使<p>
表现得像<pre>
,但如果<p>
中有任何HTML,它将丢失。
或者,您必须将它们替换为HTML换行符<br>
或<br/>
<pre>
的情况下,如果有任何HTML,则不会出现问题。在这个例子中,没有任何HTML,所以这不是一个问题。 - erosmanIf you have access to your REST api. before return comment, Use nl2br
function (php)
You can use below code in JavaScript (JS):
var comment = "This is a comment\nAnother comment\nOne more\nLast";
comment = comment.replace(/\n/g, "<br />");
alert(comment);
br
标签。使用CSS的white-space: pre-line;
可以实现相同的效果,而无需插入HTML。 - SEoF我猜这就是你想要的!!
var data = '{"comment" : "sometext\\n\\n"}'
这对我有用。
pre-line
,因为我仍然希望空格能够折叠。 - SEoF