【问题标题】:New line character in output file输出文件中的换行符
【发布时间】:2016-02-02 14:06:21
【问题描述】:

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

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

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在同一行。

有什么建议吗?

【问题讨论】:

  • 您使用的是哪个浏览器和操作系统?

标签: javascript string text-files newline


【解决方案1】:

使用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>

【讨论】:

    【解决方案2】:

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

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多