Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add line break in downloaded text file using js

I am trying to download inside div content in text format.

I can able to download inside div content in txt format but all the contents are same line .

I need to add the line break in each element.

function download() {
        var a = document.body.appendChild(
            document.createElement("a")
        );
        a.download = "export.txt";
        a.href = "data:text/html," + document.getElementById("show-data").innerHTML;
        a.click();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show-data">
<p>one</p>
<p>two</p>
<p>Three</p>
</div>
<button onClick="download()">Download</button>

https://jsfiddle.net/1L2vmdhu/

like image 773
CodeMan Avatar asked Oct 19 '25 16:10

CodeMan


1 Answers

please try with below example, as you are passing data in the form of url you have to encode new line characters which will make it work and another thing is you are trying to download as text so change content type to "text/plain"

 function download() {
        var a = document.body.appendChild(
            document.createElement("a")
        );
        var textToWrite = document.getElementById("show-data").innerText;
        a.download = "export.txt"; 
        textToWrite = textToWrite.replace(/\n/g, "%0D%0A"); 
        a.href = "data:text/plain," + textToWrite;
        a.click();
    }
  <div id="show-data">
<p>one</p>
<p>two</p>
<p>Three</p>
</div>
    <button onClick="download()">Download</button>
like image 185
Venkatesh Konatham Avatar answered Oct 21 '25 04:10

Venkatesh Konatham