The line breaks are in the generated file, but that does not mean that the program you use to read the file understands what is there.
A file can be saved with three types of control characters representing the end of a line in a text document:
-
CR
Common on Mac operating systems, comes from C R eturn.
Encoding: 0x0D (13 decimal)
-
LF
Common on Unix operating systems, comes from L F eed.
Encoding: 0x0A (10 decimal)
-
CR/LF
Common on Windows operating systems.
Any of the above line terminators is perfectly valid, but not all programs understand them, resulting in the file's contents appearing on one line.
Solution
The solution is to make use of the line terminator that suits us, where for that purpose, after reading the text to be saved, we manipulate it to standardize the results.
Because browsers use different line terminators, each other: \r
or \n
or \r\n
respectively, the most likely seems to be the use of the appropriate line terminator for the user's operating system.
So here's an example below to test and perform a simple test of typing two or more lines of text and clicking a button.
What will happen is:
- Read the value of
textarea
;
- Separate text into an array where each entry is a read line, using a regular expression that looks for the 3 possible line terminators;
-
Re-merge the text with the appropriate line terminator for the detected operating system:
We make use of the information provided by the navigator.appVersion
property and try to locate an operating system prompt to return the corresponding line terminator:
function qualOS() {
var x = "\r\n";
if (navigator.appVersion.indexOf("Win") != -1) x = '\r\n';
if (navigator.appVersion.indexOf("Mac") != -1) x = '\r';
if (navigator.appVersion.indexOf("X11") != -1) x = '\n';
if (navigator.appVersion.indexOf("Linux") != -1) x = '\n';
return x;
}
-
Trigger an alert to see the text.
Example
function qualOS() {
var x = "\r\n";
if (navigator.appVersion.indexOf("Win") != -1) x = '\r\n';
if (navigator.appVersion.indexOf("Mac") != -1) x = '\r';
if (navigator.appVersion.indexOf("X11") != -1) x = '\n';
if (navigator.appVersion.indexOf("Linux") != -1) x = '\n';
return x;
}
function testar() {
var texto = document.getElementById("texto").value;
var linhas = texto.split(/\r\n|\r|\n/g);
var textoFinal = linhas.join(qualOS());
alert(textoFinal);
}
textarea {
width: 400px;
height: 200px;
}
<textarea id="texto"></textarea>
<p>
<button onclick="testar()">testar</button>
</p>
This code, in your case, will be applied between the reading of the value of textarea
and the generation of blob
:
function saveTextAsFile() {
var textToWrite = document.getElementById("inputTextToSave").value;
// aqui, fazer aqui a verificação e conversão do terminado de linha
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
// ...
}