0

I'm importing a text file from an outside directory into an html paragraph tag to be displayed when a button is clicked. I'm using jQuery's .load() function to do this.

The text file gets imported no problem, but the format is not kept,

The imported text file 'banks.txt' comes through as:

"Love Poem Serene, In a world full of troubles, i.e. doing nothing about it. - Iain Banks"

instead of:

Love Poem

Serene,
In a world full of troubles,
i.e. doing nothing about it.

- Iain Banks

Is there a way to keep the text-file's formatting- newlines, tabs, and all?

Samuel Ludwig
  • 111
  • 1
  • 7
  • 1
    Try loading it into a `
    ` element, or [replacing all newlines with HTML line-breaks](https://stackoverflow.com/a/784547/2026606). Related: https://stackoverflow.com/questions/4440033/problem-with-jquery-load-method-and-newlines-in-internet-explorer
    – Tyler Roper Jul 13 '18 at 18:40

1 Answers1

0

You should load the text file into a pre tag as text in a pre element is displayed in a fixed-width font, and it preserves both spaces and line breaks. Try this for Internet Explorer (which behaves differently; just loading the text file into a pre tag should be fine for other browsers):

$("#data pre").load("lorem.txt", function(response, status, xhr) {
   if (status != "error") {
   if (($.browser.msie)&&(jQuery.browser.version=="8.0"))//check if browser is Internet Explorer
    $("#data pre").html(response.replace(/\r\n/g, "<br>"));//replace new lines with <br> tag
   }
});

HTML:

 <div id="data">
 <pre></pre>
 </div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80