输出文件中的换行符

New line character in output file

本文关键字:换行符 文件 输出      更新时间:2023-09-26

当我试图将一个包含多行的字符串写入输出文本文件时,换行符将不会保留,所有内容都打印在一行上。

在特定的我有一个按钮与一个监听器点击与相关的这个功能:

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

文件已正确下载,但字符串1、字符串2和字符串3位于同一行。

有什么建议吗?

我认为您可能需要对数据进行编码,可以使用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>