输出文件中的换行符

New line character in output file

当我尝试将多行字符串写入输出文本文件时,换行符未保留,所有内容都打印在一行上。

具体来说,我有一个带有点击监听器的按钮,与此功能相关联:

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);
}

文件正确下载,但string1、string2和string3在同一行。

有什么建议吗?

我认为您可能需要对数据进行编码,您可以使用 encodeURIComponent()

试试这个:

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

使用encodeURIComponent()。请参阅下面的工作示例。

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>