.html () of a request not storing a new line feed

I am adding data to jQuery Accordion as follows

$('<div>').append($('<p>').attr('style', 'font-size:10px').html(strData)); 

where my strData is the string coming from the database. This line has line breaks, but as soon as it joins, it loses all its line break and shows on one line. For the same data, when in warning mode it is displayed as I want. How is this caused and how can I solve it?

+4
source share
3 answers

In HTML, linebreaks are represented by <br> tags, not CRLF characters.

You need to either replace the CRLF characters with <br> tags, or to apply CSS white-space:pre to the containing HTML element, and use text() instead of html() .

Replacing CRLF with <br> can be done in various ways. On the server side, before returning strData to JavaScript. For example, when you use Java:

 strData = strData.replace("\\n", "<br />"); 

Or on the client side using JavaScript itself:

 strData = strData.replace(/\n/g, "<br />"); 
+10
source

Replace line breaks with <br> :

 strData.replace(/\r\n|\r|\n/g,"<br>") 

This regular expression takes into account the difference in OS-specific characters at the end of line characters. Win - \ r \ n, Unix - \ n, Mac - \ r

+1
source

BalusC is true. If you cannot format the data in a database, you can also do this:

 strData = strData.replace(/\r?\n|\r/g, "<br/>"); $('<div>').append($('<p>').attr('style', 'font-size:10px').html(strData)); 

Which will replace all lines in your line with the tag "br"

+1
source

All Articles