.txt文件中的textarea内容但保留换行符

时间:2015-05-14 07:27:10

标签: javascript html textarea line-breaks

我有一些代码可以将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/

有没有办法保留这些换行符?请帮帮我!感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用replace

像这样:

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

SEE DEMO