Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display new line in .text() in jQuery?

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.

like image 400
User4678 Avatar asked Aug 06 '13 03:08

User4678


People also ask

How do you add a new line in jQuery?

You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.

What is text () in jQuery?

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.

What is $() in jQuery?

$() = 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.

How do I add a new line to a string in HTML?

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.


1 Answers

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;
like image 144
Blender Avatar answered Sep 23 '22 13:09

Blender