I have an application in which I receive a comment string from REST Api like this
"comments":"This is a comment\nAnother comment\nOne more\nLast
Run Code Online (Sandbox Code Playgroud)
I'm displaying it using p tag but it's not recognizing line breaks(\n). How to have a newline?
jno*_*dim 15
可能是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.'
}Run Code Online (Sandbox Code Playgroud)
p.no-breaks {
white-space: nowrap;
color: red;
}
p.with-breaks {
white-space: pre-wrap;
color: blue;
}Run Code Online (Sandbox Code Playgroud)
<p class="no-breaks">This text will be replaced.</p>
<p class="with-breaks">This text will be replaced.</p>Run Code Online (Sandbox Code Playgroud)
<pre>标签设置为识别换行符。您可以通过 CSS使<p>行为类似于<pre>,但您将丢失<p>(如果有)中的任何 HTML 。
或者,您必须将它们替换为 HTML 换行符<br>或<br/>
有两种方法:
如果您有权访问 REST api。在返回注释之前,使用nl2br函数(php)
您可以在 JavaScript (JS) 中使用以下代码:
var comment = "This is a comment\nAnother comment\nOne more\nLast";
comment = comment.replace(/\n/g, "<br />");
alert(comment);
Run Code Online (Sandbox Code Playgroud)我想这就是你想要的!!
var data = '{"comment" : "sometext\\n\\n"}'
Run Code Online (Sandbox Code Playgroud)
它对我有用..