3

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

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

Thanks.

3
  • @user285677 Few people will want to help you if you don't accept valid answers to your questions. Commented Jan 2, 2011 at 20:03
  • possible duplicate of display mysql newline in HTML Commented Jan 2, 2011 at 20:07
  • You can see an example of using .replace() method here lampcoder.com/… Commented Aug 16, 2012 at 11:59

3 Answers 3

7

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"/> 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 <pre> tag.
I think you mean the CSS property white-space not whitespace.
5
foo.innerHTML = myObj.s.replace(/\n/g,"<br>"); 

5 Comments

changed to foo.innerHTML = myObj.s.replace(/\n/g,"<br />");
you might need to escape the \ charater /\\n/g
@benbyford No, you don't.
@benbyford The OP's code shows a single ASCII newline character. In a literal regex, that is represented as \n. If you wrote /\\n/ it would match two ASCII characters, a backslash followed by a letter n.
sorry was getting confused as \ is used to escape characters but maybe not in this context then it would appear
2
{"s", "phrase1.<br /><br />"phrase2"} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.