Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add JavaScript String with line breaks and tabs to HTML element

I have this HTML:

<p id="element">Waiting for Message</p>

And this string from the server using JSON.stringify() with breaks and tabs in it i.e

var = "Heading (info:info) \n info: \n \t and so on "; // The actual string is more complex though, just an example

And this Jquery to post the string to the paragraph tag:

$("#element").text(data); // data is the string from the server(not in JSON!)

The problem is the HTML ignores the formatting but when I use an alert box it displays with the proper formatting. I am dynamically updating the element as data comes from the server. Any pointers?

like image 922
IskandarG Avatar asked Oct 07 '16 13:10

IskandarG


People also ask

How do you show line breaks in HTML?

The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems.

How do you insert a line break in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do you put a space in a string in JavaScript?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!


3 Answers

You should tell browser to respect those whitepaces. Easy way to do it is using white-space: pre rule:

var data = "Heading (info:info) \n info: \n \t and so on "; 

$("#element").html(data);
#element {
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="element">Waiting for Message</p>
like image 83
dfsq Avatar answered Oct 09 '22 00:10

dfsq


Make use of the pre tag in HTML and update your text there

$(document).ready(function(){

var data = {
    "id": "1",
    "nome": "erwrw",
    "cognome": "sdsfdfs",
    "CF": "qwert",
    "eta": "27",
    "sesso": "uomo",
    "indirizzo": "qwerrt",
    "luogo": "wewrw",
    "provincia": "ewrewrw",
    "citta": "erwrwr",
    "comune": "ewrewrw"
  }

var obj = JSON.stringify(data, null, 4);
$('#element').text(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="element">Waiting for Message</pre>
<button id="btn">send</button>
like image 4
Shubham Khatri Avatar answered Oct 09 '22 00:10

Shubham Khatri


$("#element").html(data.replace(/(\n)/g, '<br>'));
like image 1
Diptox Avatar answered Oct 08 '22 22:10

Diptox