17

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.

1
  • var stringDisplay = "Hello<br />World"; $("#meaning").html(stringDisplay); Commented Aug 6, 2013 at 3:03

2 Answers 2

30

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;
Sign up to request clarification or add additional context in comments.

4 Comments

This answer is not complete. You must set the text first, to properly escape any HTML that is in the text. Only then can you do your line replacement (assuming the new line is still there).
$('#meaning').html(escaped.replace(/\n/g, '<br />')); worked.. thanks a lot
adding style white-space: pre-wrap; works best for me.
Escaping doesn't work at all. jsfiddle.net/h27vxenm
10

How about this

$('meaning').html('line1<br>line2');

1 Comment

Would be painful if line1 or line2 is user input

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.