Andrea
Andrea

Reputation: 566

New line character in output file

When I try to write a string with multiple lines to an output text file the newline chars are not preserved and all the content is printed on one single line.

In the specific I have a button with a listener on click with associated this function:

function (e) {
    this.downloadButton.setAttribute("download", "output.txt");
    var textToSend = string1+"\r\n"+string2+"\r\n"+string3;
    this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend);
}

The file correctly downloaded, but string1, string2 and string3 are on the same line.

Any suggestion?

Upvotes: 10

Views: 6378

Answers (2)

Andrew Mairose
Andrew Mairose

Reputation: 10995

Use encodeURIComponent(). See working example below.

var downloadButton = document.getElementById('download');
var textToSend = encodeURIComponent("string1\r\nstring2\r\nstring3");
downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend);
<a id="download" download="output.txt">Download</a>

Upvotes: 4

musefan
musefan

Reputation: 48415

I think you may need to encode your data, which you can do with encodeURIComponent().

Try this:

var textToSend = string1+"\r\n"+string2+"\r\n"+string3;
textToSend = encodeURIComponent(textToSend);
this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend)

Upvotes: 8

Related Questions