如何在 HTML 中识别换行符 (\n)

12

我有一个应用程序,从REST API接收评论字符串如下:

"comments":"This is a comment\nAnother comment\nOne more\nLast

我使用p标签展示文本,但是它不能识别换行符(\n)。如何实现换行?

4个回答

14

这可能与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>


1
这是正确的答案!当然,用JS将“\n”替换为“<br>”很容易,但那时你可能正在从某种编辑器中输入文本,并且不想允许其他HTML通过,但你已经把自己置于了必须过滤掉HTML然后自己进行替换的情况下。使用这个方法,不需要JS hack。我正在使用Vue.js,并且不想因为刚才提到的原因而切换到v-html。我个人使用了pre-line,因为我仍然希望空格能够折叠。 - SEoF

9

<pre>标签是设置识别换行符的。您可以通过CSS使<p>表现得像<pre>,但如果<p>中有任何HTML,它将丢失。

或者,您必须将它们替换为HTML换行符<br><br/>


但您将失去<p>中的任何HTML;我不明白您的意思。 - Protagonist
1
@Protagonist.. 正如我所说,在 <pre> 的情况下,如果有任何HTML,则不会出现问题。在这个例子中,没有任何HTML,所以这不是一个问题。 - erosman

5
有两种方式:
  1. If you have access to your REST api. before return comment, Use nl2br function (php)

  2. 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);
    

虽然这个方法可行,但要小心陷阱——如果文本来自用户输入,而你不想允许其他HTML,则必须先清理文本。像Vue.js、Lodash甚至jQuery这样的库和工具可以让你设置文本而不是设置HTML,这有效地防止了HTML,但它们也会阻止br标签。使用CSS的white-space: pre-line;可以实现相同的效果,而无需插入HTML。 - SEoF

0

我猜这就是你想要的!!

var data = '{"comment" : "sometext\\n\\n"}'

这对我有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接