【问题标题】:textarea content inside a .txt file but keep line-breaks.txt 文件中的 textarea 内容,但保留换行符
【发布时间】:2015-07-25 17:40:52
【问题描述】:

我有一些代码可以将 textarea 的值保存到本地文本文件中。一切似乎都很好,但我不想失去换行符。代码和小提琴:

HTML

<textarea id="textbox">Type something here</textarea> 
<button id="create">Create file</button> 
<a download="info.txt" id="downloadlink" style="display:none">Download</a>

JS

(function () {
    var textFile = null,
        makeTextFile = function (text) {
            var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);
    return textFile;
    };

    var create = document.getElementById('create'),
        textbox = document.getElementById('textbox');

    create.addEventListener('click', function () {
        var link = document.getElementById('downloadlink');
        link.href = makeTextFile(textbox.value);
        link.style.display = 'block';
    }, false);

})();

http://jsfiddle.net/qm5AG/562/

有什么方法可以保留这些换行符吗?请帮帮我!谢谢。

【问题讨论】:

    标签: javascript html textarea line-breaks


    【解决方案1】:

    你可以使用replace

    像这样:

    text = text.replace(/\n/g, "\r\n");
    var data = new Blob([text], {type: 'text/plain'});
    

    SEE DEMO

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 2015-08-16
      • 1970-01-01
      • 2018-06-11
      • 2019-02-22
      • 1970-01-01
      • 2015-12-21
      相关资源
      最近更新 更多