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?
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?
Share Improve this question asked Nov 2, 2015 at 16:06 AndreaAndrea 5661 gold badge6 silver badges23 bronze badges 1- which browser and os are you using? – baao Commented Nov 2, 2015 at 16:10
2 Answers
Reset to default 8I 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)
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>