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

新手上路,请多包涵

我有一个应用程序,我在其中收到来自 REST Api 的评论字符串,如下所示

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

我正在使用 p 标签显示它,但它无法识别换行符 (\n)。如何换行?

原文由 Protagonist 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.2k
1 个回答

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

原文由 jnotelddim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏