user811433
user811433

Reputation: 4149

How to write newline using jquery?

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?

Upvotes: 2

Views: 4725

Answers (4)

baao
baao

Reputation: 73291

Convert the line breaks to <br>s

$("#divId).html(result.replace(/\n/g, "<br />"));

Upvotes: 3

user5450651
user5450651

Reputation:

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

Upvotes: 0

Volkan Ceylan
Volkan Ceylan

Reputation: 1496

  $('#divId').html("<pre>" + result + "</pre>");

Upvotes: 2

brianpck
brianpck

Reputation: 8254

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.

Upvotes: 0

Related Questions