Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

Maybe .text instead of .html?


Use <br /> for new line in html:

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

Set your css in the table cell to

white-space:pre-wrap;

document.body.innerHTML = 'First line\nSecond line\nThird line';
body{ white-space:pre-wrap; }