11

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?

Protagonist
  • 1,649
  • 7
  • 34
  • 56

4 Answers4

13

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>
jnotelddim
  • 1,806
  • 17
  • 32
  • 1
    This is the correct answer! Sure, it's easy to replace "\n" with "
    " 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
8

<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/>

erosman
  • 7,094
  • 7
  • 27
  • 46
5

There is two way:

  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);
    
MahdiY
  • 1,269
  • 21
  • 32
  • Whilst this works, beware of dragons - if the text came from a user input where you don't want to allow other HTML, you'll have to clean the text first. Libraries and tools like Vue.js, Lodash, and even jQuery give you a way to set the text instead of setting the HTML, which effectively prevents HTML, but they will also prevent the `br` tags. Using CSS `white-space: pre-line;` achieves the same affect without needing to insert HTML. – SEoF Aug 12 '21 at 10:55
0

I guess this is what you want!!

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

It worked for me..

Abizz
  • 216
  • 2
  • 16