3

If I set the following string into a div how can I get the newline working at HTML?

{
"s":"Phrase1.\n\nPhrase2"
}

Thanks.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
user285677
  • 1,098
  • 3
  • 14
  • 21
  • @user285677 Few people will want to help you if you don't accept valid answers to your questions. – Phrogz Jan 02 '11 at 20:03
  • possible duplicate of [display mysql newline in HTML](http://stackoverflow.com/questions/1882754/display-mysql-newline-in-html) – Tomalak Jan 02 '11 at 20:07
  • You can see an example of using `.replace()` method here http://www.lampcoder.com/how-to-parse-line-breaks-using-jquery-post-method-and-json/ – Mihai Matei Aug 16 '12 at 11:59

3 Answers3

6

Wrap preformatted text in <pre> tags:

<pre>{ "s":"Phrase1.\n\nPhrase2" }</pre>

Shows up as:

{ "s":"Phrase1.

Phrase2" }

Edit: Another option would be to set the div's style or class to behave the same as a pre tag:

<div style="whitespace:pre"/>
Ed Marty
  • 39,590
  • 19
  • 103
  • 156
  • Given that the subject and tag includes "JSON" I assume the OP is accessing an `s` property of a JSON return value and setting text to that value. – Phrogz Jan 02 '11 at 20:04
  • Well, it is a json-formatted string. It may have nothing to do with Javascript JSON object. Even if it does, you could still wrap the contents in a
     tag.
    – Ed Marty Jan 03 '11 at 00:17
  • I think you mean the CSS property `white-space` not `whitespace`. – Ludo - Off the record Aug 17 '22 at 16:01
5
foo.innerHTML = myObj.s.replace(/\n/g,"<br>");
Phrogz
  • 296,393
  • 112
  • 651
  • 745
2
{"s", "phrase1.<br /><br />"phrase2"}
calin
  • 58
  • 5