I have the following code:
var stringDisplay = "Hello\nWorld";
$("#meaning").text(stringDisplay);
It is displaying \n
instead of a newline.
The output is showing up as Hello\nWorld
.
I used <br>
tag also in place of \n
, but it's still not working.
You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.
jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
You will have to use both .html()
and replace the newline:
var escaped = $('<div>').text(stringDisplay).text();
$('#meaning').html(escaped.replace(/\n/g, '<br />'));
An alternative would be to style the element:
white-space: pre-wrap;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With