最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - New line character in output file - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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)

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>

发布评论

评论列表(0)

  1. 暂无评论