Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.html() of query not preserving the new line feed

Tags:

jquery

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?

like image 956
saurabhsingh Avatar asked Dec 10 '22 07:12

saurabhsingh


2 Answers

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 />");
like image 104
BalusC Avatar answered Jan 28 '23 14:01

BalusC


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

like image 43
VIK Avatar answered Jan 28 '23 13:01

VIK