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?

5
  • 3
    You can use <br> Commented Sep 30, 2016 at 18:38
  • 2
    Highlight the text and view the source: it has newlines. You are looking for an html <br>, not a newline. Commented Sep 30, 2016 at 18:39
  • Java is to javascript as car is to carpet. And for a laugh: stackoverflow.com/a/245073/870729 Commented Sep 30, 2016 at 18:44
  • See stackoverflow.com/questions/8573890/… Commented Sep 30, 2016 at 18:45
  • <br> helped for the text. Thank you! The file also has some formatted table content. This was written to the file using String.format(). Is there a way to retain that formatting when writing the result in front-end? Commented Sep 30, 2016 at 18:46

4 Answers 4

3

Convert the line breaks to <br>s

$("#divId).html(result.replace(/\n/g, "<br />"));
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it. :)
Need to make it global otherwise it will works on first new line only
2
  $('#divId').html("<pre>" + result + "</pre>");

5 Comments

<pre> has a specific semantic meaning. It is not a lazy way to avoid HTML tags.
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.
You're confusing display and semantics: w3.org/TR/html5/grouping-content.html#the-pre-element
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.
Using <pre> helped retain the formatting of the tables that were present in the text file. Thank you!
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.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.