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

Solution 1:

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; }

Solution 2:

Use <br /> for new line in html:

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

Solution 3:

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>

Solution 4:

Maybe .text instead of .html?