See: Multiline strings in ES6 JavaScript
Your issue is that you are not retrieving the text from a word processor or notepad (which preserves new lines). You are defining the string value IN-LINE with the code.
Update: Incorporated a function call into the string.
You either need to place literal new-lines at the end of each line.
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);
}
function getLastUpdated() {
return `\nLast updated: ${new Date().toISOString()}`;
}
// Start file download.
document.getElementById("dwn-btn").addEventListener('click', function(){
// Generate download of hello.txt file with some content
var text = `A rather long string of English text, an error message \n
actually that just keeps going and going -- an error \n
message to make the Energizer bunny blush (right through \n
those Schwarzenegger shades)! Where was I? Oh yes, \n
you\'ve got an error and all the extraneous whitespace is \n
just gravy. Have a nice day \n
${getLastUpdated()}`;
var filename = "hello.txt";
download(filename, text.replace(/\n/g, '\n\r')); // Convert LF ro LFCR
}, false);
<input type="button" id="dwn-btn" value="Download" />
Or, join the lines together inside of an array. There is no other way to do this. The back-ticks and back-slashes ignore new lines. Visually having new-lines in the code does not translate to new-lines in the text. It just makes it easier for YOU to see the new lines.
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);
}
function getLastUpdated() {
return `\n\nLast updated: ${new Date().toISOString()}`;
}
// Start file download.
document.getElementById("dwn-btn").addEventListener('click', function(){
// Generate download of hello.txt file with some content
var text = [
'A rather long string of English text, an error message',
'actually that just keeps going and going -- an error',
'message to make the Energizer bunny blush (right through',
'those Schwarzenegger shades)! Where was I? Oh yes,',
'you\'ve got an error and all the extraneous whitespace is',
'just gravy. Have a nice day',
getLastUpdated()
].join('\n');
var filename = "hello.txt";
download(filename, text.replace(/\n/g, '\r\n')); // Convert LF ro CRLF
}, false);
<input type="button" id="dwn-btn" value="Download" />
Your multiline text