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
I'm displaying it using p tag but it's not recognizing line breaks(\n). How to have a newline?
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
I'm displaying it using p tag but it's not recognizing line breaks(\n). How to have a newline?
It may be an issue of the CSS,
if you apply white-space: pre-wrap
, then it may help ensure your linebreaks are recognized.
See docs for other white-space
options & what they do.
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>
tag is set to recognize newlines. You can make the <p>
behave like <pre>
via CSS but you will loose any HTML in the <p>
(if there are any).
Alternatively, you have to replace them with HTML linebreak <br>
or <br/>
`, if there are any. In the example, there weren't any HTML so that was not an issue.– erosman Mar 02 '17 at 20:02
There is two way:
If 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);
I guess this is what you want!!
var data = '{"comment" : "sometext\\n\\n"}'
It worked for me..
" with JS, but then you're probably entering the text from some sort of editor and don't want to allow other HTML through, but you've forced yourself into a situation where you have to filter out HTML then do the replacement yourself. With this, no JS hack is needed. I'm using Vue.js, and didn't want to switch to v-html for the reasons I've just stated. I personally used `pre-line` as I still wanted spaces to collapse. – SEoF Aug 12 '21 at 10:51