The application creates a file:

function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } 
 <div id = "div_with_text">some<br/>text</div> <a href = "javascript:download('text.txt', document.getElementById('div_with_text') .textContent)" id = "save" style = "margin-bottom:0px;">save file.</a> 

However, in the file thus obtained there are no line breaks. Do not tell me, can this be somehow fixed?

  • <br/> This is an HTML line break element, in the text it is responsible for \r\n - LamerXaKer
  • just see what textContent returns to you - Grundy
  • You can try to change all <br> first in the received javascript line and then write to the file. str = str.replaceAll("<br />", "\r\n"); - LamerXaKer
  • textContent returns me the text with hyphenation (output via console.log ()), and str = str.replaceAll ... gave nothing ((( - nita
  • Even probably something like this document.getElementById('div_with_text').textContent.replace("<br/>", "\r\n"); - LamerXaKer

1 answer 1

<br/> This is an HTML line HTML element, in the text it is responsible for \r\n (it may depend on the system, win it, * nix or OSX)

You can first try to change all <br> to \r\n in the received javascript line and then write to the file.

str = str.replaceAll("<br/>", "\r\n");

In your case, it might look like this:

document.getElementById('div_with_text').innerHTML.replace("<br/>", "\r\n");

Perhaps after document.getElementById('div_with_text').textContent it doesn’t display <br/> but single \r or \n . Then you can try this option:

document.getElementById('div_with_text').textContent.replace("(\r|\n)", "\r\n");