I am appending data to jQuery Accordion like this
$('<div>').append($('<p>').attr('style', 'font-size:10px').html(strData));
where my strData is a line coming from database. This string has line breaks, but once it get appended, it loses all its line break and show in one line. For the same data when in alert it, it shows as I want. How is this caused and how can I solve it?
In HTML, linebreaks are represented by <br>
tags, not by CRLF characters.
You need to either replace CRLF characters by <br>
tags, or to apply CSS white-space:pre
on the containing HTML element and use text()
instead of html()
.
Replacing CRLF by <br>
can be done at various ways. In the server side before returning the strData
to JavaScript. For example, when you're using Java:
strData = strData.replace("\\n", "<br />");
Or in the client side using JavaScript itself:
strData = strData.replace(/\n/g, "<br />");
Replace the string breaks with <br>
:
strData.replace(/\r\n|\r|\n/g,"<br>")
This regexp should take into account OS-dependent difference in line-end symbols. Win - \r\n, Unix - \n, Mac - \r
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With