在字符串中使用新行(n) ,并在 HTML 中显示相同的内容

我有一个字符串说

string display_txt = "1st line text" +"\n" + "2nd line text";

在 Jquery 中,我试图使用

('#somediv').html(display_txt).css("color", "green")

很明显,我希望我的 msg 显示在2行,但是 n 显示在消息中。有什么快速解决办法吗?

谢谢,

264589 次浏览

Use <br /> for new line in html:

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

Maybe .text instead of .html?

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

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>

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