Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve newlines when showing a text file with jQuery

I want to fetch the content of an text file and I have manage to do that. Everything is working except for one thing - detecting new lines.

My solution to fetch the content in the text file:

$.ajax({
    url: '/nhagyavi/files/textfiles/changelog.txt',
    success: function(data) {
        $('#load-changelog').html('<div style="font-family: Courier New;">' + data + '</div>');
    }
});

The content of the text file:

2012-03-15: Snabbfixar
- Detta är en fin liten rad som berättar vad som är nytt
- En till rad, tillsammans med en <a href="javascript:void(0)">länk</a>

How the result looks like on my page:

2012-03-15: Snabbfixar - Detta är en fin liten rad som berättar vad som är nytt - En till rad, tillsammans med en länk

I don't know how I can use print_r in jQuery so I can't really see how the lines really looks like. Anyone who knows how I can fix my problem?

like image 622
Airikr Avatar asked Mar 15 '12 19:03

Airikr


People also ask

How do I preserve line breaks in textarea?

If you want your text to overflow the parent's boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces. Enjoy!

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do you preserve a new line in HTML?

Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

How add BR tag to textarea?

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' .


1 Answers

Add white-space:pre-line; to your container:

#load-changelog {
    white-space: pre-line;
}

Simplified demo: http://jsfiddle.net/tF3Mb/1/

If you also want to show all space characters, use white-space:pre instead of pre-line: http://jsfiddle.net/tF3Mb/

like image 55
Rob W Avatar answered Oct 21 '22 18:10

Rob W