html() & text() ignoring \n and <br />

I don’t understand why this is happening, basically i got some description of some app from Google play store, in the form of JSON, now i am using jQuery to add the description into some div, but instead of actually printing as it is, it gives a block of paragraph and ignores \n or <br /> tag.

var description = json.description;

When I alert this description, as shown above, there is proper paragraph format with next line[\n] included just like I want it, but when I add it to the required div with either html() or text(), it ignores the next line \n


I tried to replace the next line with the
tags, but still the result was same, I don’t know why

var test = description.replace(/\s\n+/g, '<br />');

31 thoughts on “html() & text() ignoring \n and <br />”

  1. Try this

    var test = description.replace(/\n/g, '<br />');
    $('#appName').html(test );

    Your regex would not work if there is no white space before newline character. also you dont need to put + as /g will replace all new line characters.

  2. Use a regular expression for .replace().:

    $('#appName').html(description.replace(/\n/g, "<br />"));

    If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

    $('#appName').html(description.replace(/\r\n/g, "<br />"));

Leave a Comment