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

JqueryHtmlStringNewline

Jquery Problem Overview


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,

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

Use <br /> for new line in html:

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

Solution 3 - Jquery

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 - Jquery

Maybe .text instead of .html?

Solution 5 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeenUserView Question on Stackoverflow
Solution 1 - JqueryvsyncView Answer on Stackoverflow
Solution 2 - JquerySamichView Answer on Stackoverflow
Solution 3 - JqueryFrank im WaldView Answer on Stackoverflow
Solution 4 - Jqueryuser1046334View Answer on Stackoverflow
Solution 5 - JqueryKevin H GriffithView Answer on Stackoverflow