Search code examples
javascriptjqueryhtmljquery-mobile

Losing line break when displaying text


I can see the line breaks "↵" for a string in Chrome Developer Tools

<br>↵↵<br>Event Status: confirmed↵<br>Event Description: Hog Day (Night )and Hog Day (Day)↵↵Friday...

If i double click this and paste to Notepad, the line breaks are preserved.

When i save the string to an object like so,

var summary = el.find("summary").text();
var volunteerEvent = {title: title, summary: summary}

and eventually display it on a page,

$('#volunteerEventDescription').empty().html(event.summary);

the line breaks are gone and it's a huge chunk of text.

How do i keep the newlines?


Solution

  • I see two obvious options. Which one is the right one for you depends on how much control over the formatting you want.

    1. Use the pre tag and the new lines will be respected. pre is for preformatted text and will use non-proportional font so it may not render as you would wish. See pre on MDN for more details.

    2. Replace the new lines with the br tag. You can do this with a regular expression: stringValue.replace(/\n/g, '<br/>'). A more robust regular expression is present on another question: jQuery convert line breaks to br (nl2br equivalent).

    As an update in 2023, another option is to use the CSS white-space pretty with pre, pre-wrap or pre-line as the value. See MDN white-space page for more details.