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.

share|improve this question
    
var stringDisplay = "Hello<br />World"; $("#meaning").html(stringDisplay); – andrewb Aug 6 '13 at 3:03

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;
share|improve this answer
    
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). – Brad Aug 6 '13 at 3:13
    
@Brad: Thanks, fixed. – Blender Aug 6 '13 at 3:17
    
$('#meaning').html(escaped.replace(/\n/g, '<br />')); worked.. thanks a lot – User4678 Aug 6 '13 at 9:08
    
adding style white-space: pre-wrap; works best for me. – Troy Harris Mar 24 '17 at 16:19

How about this

$('meaning').html('line1<br>line2');
share|improve this answer
    
Would be painful if line1 or line2 is user input – Memet Olsen Jun 18 '16 at 15:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.