Amy
Amy

Reputation: 946

Unable to retain line breaks when writing text file as blob

I have a text area that contains text that I want to output to a text file for users to download.

I'm using this function to grab it when users click the save button

function saveTextAsFile()
{
    var textToWrite = document.getElementById("inputText").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    alert(textFileAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

But the line breaks aren't retained. They exist in document.getElementById("inputText").value; but not in the text file created from the blob.

Upvotes: 17

Views: 21629

Answers (4)

efrat v
efrat v

Reputation: 1

I had a similar problem, when the text arrived from JSON. the solution was:

 textToWrite.replaceAll('\\r\\n',"\r\n")

Upvotes: 0

Vinu
Vinu

Reputation: 89

change

var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});

to

var textFileAsBlob = new Blob([textToWrite], {type:'text/plain',endings:'native'});

May not work in IE and I dont know how to fix it

Upvotes: 4

nihlton
nihlton

Reputation: 659

I ran into the same problem. This seems to be working for me:

textToWrite = textToWrite.replace(/\n/g, "\r\n");

Upvotes: 38

Lambros
Lambros

Reputation: 151

You should put something like that into your code.

textToWrite.replace(/\r?\n/g, '<br />');

Upvotes: -5

Related Questions