I have a string say
string display_txt = "1st line text" +"\n" + "2nd line text";
in Jquery, I am trying to use
('#somediv').html(display_txt).css("color", "green")
quite clearly I am expecting my msg to be displayed in 2 lines, but instead \n is being displayed in the message. Any quick fixes for that?
Thanks,
Maybe .text
instead of .html
?
I had the following problem where I was fetching data from a database and wanted to display a string containing \n
. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208
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>
Set your css in the table cell to
white-space:pre-wrap;
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
Source: Stackoverflow.com