How can I take the value of a textarea and that when I store it in a variable, respect the jumps of textarea lines and spaces?

1

I have a section for quick notes but when I save them in a file ( .txt ) it saves me the value of the textarea in a single line and I want to respect the line breaks and spaces;

Example:

Value or text that entered textarea:

  

HELLO WORLD
  HELLO WORLD
  HELLO WORLD
  HELLO WORLD

Value that you save in the file (.txt):

  

HOLAMUNDOHOLAMUNDOHOLAMUNDOHOLAMUNDO

HTML code

<textarea placeholder="Escribir..." 
          id="input_textarea" 
          style="width: 370px; 
                 height: 150px; 
                 margin-top: 25px; 
                 margin-left: 16px; 
                 margin-right: 16px;">
</textarea>

JavaScript code

function guardar_notas_txt()
    { 
        var textToWrite = input_textarea.value;
        var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
        var file_name = nombre_guardado_notas.value;
        var fileNameToSaveAs = file_name+".txt";
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "My Hidden Link";
        window.URL = window.URL || window.webkitURL;
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
        downloadLink.click();
    }

function destroyClickedElement(event)
    {
        document.body.removeChild(event.target);
    }
    
asked by Erick Hammett 16.08.2018 в 00:03
source

1 answer

1

Try this regex function when you capture the value of your textarea :

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

Demo:

function guardar_notas_txt() {

  var textToWrite = input_textarea.value.replace(/\n/g, "\r\n");
  var textFileAsBlob = new Blob([textToWrite], {
    type: 'text/plain'
  });
  var file_name = "archivo";
  var fileNameToSaveAs = file_name + ".txt";
  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "My Hidden Link";
  window.URL = window.URL || window.webkitURL;
  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  downloadLink.onclick = destroyClickedElement;
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);
  downloadLink.click();
}

function destroyClickedElement(event) {
  document.body.removeChild(event.target);
}
<textarea placeholder="Escribir..." id="input_textarea" style="width: 370px; 
                 height: 150px; 
                 margin-top: 25px; 
                 margin-left: 16px; 
                 margin-right: 16px;">
</textarea>
<br>
<button onclick="guardar_notas_txt();">Guardar</button>
    
answered by 16.08.2018 / 00:19
source