2

There is a formatted txt file that my java program reads and sends over the contents as a string to front-end. The string that is sent to front end looks like this:

var result = "This is the result.\nIt contains some details\n\nDetails are as follows\nabc,xyz"

In the frontend, This data must be written to a div in the following format:

This is the result.
It contains some details

Details are as follows
abc,xyz

Using the following code did not work:

$("#divId).html(result);

Alternates like val(), text() did not work either. How can I make the browser write the new lines in the div when displaying the result?

user811433
  • 3,999
  • 13
  • 53
  • 76

4 Answers4

3

Convert the line breaks to <br>s

$("#divId).html(result.replace(/\n/g, "<br />"));
baao
  • 71,625
  • 17
  • 143
  • 203
2
  $('#divId').html("<pre>" + result + "</pre>");
Volkan Ceylan
  • 1,486
  • 13
  • 15
  • 2
    `
    ` has a specific semantic meaning. It is not a lazy way to avoid HTML tags.
    – brianpck Sep 30 '16 at 18:45
  • it means this text is preformatted, leave it as is. it can be further customized with another font, and css. i don't think it's that bad. he still should html encode the message though. – Volkan Ceylan Sep 30 '16 at 18:50
  • You're confusing display and semantics: https://www.w3.org/TR/html5/grouping-content.html#the-pre-element – brianpck Sep 30 '16 at 18:52
  • and am i supposed to read that thing because someone who thinks he knows everything better said so. i'm not confusing anything, you just don't have respect. – Volkan Ceylan Sep 30 '16 at 18:56
  • Using
     helped retain the formatting of the tables that were present in the text file. Thank you!
    – user811433 Sep 30 '16 at 19:40
0

Let's consider a simple HTML source file.

Hello

2 new lines.



3 new lines.

Let's consider another one:

Hello<br>The magic of HTML tags!

You are confusing newlines with HTML <br> tags.

brianpck
  • 8,084
  • 1
  • 22
  • 33
0

Use like this

var result = "This is the result.\nIt contains some details\n\nDetails are as follows\nabc,xyz" 
var res = result.replace(/\n/g, "<br>");
$("#divId).html(res);