surya surya - 6 months ago 55
Javascript Question

no newlines in generated CSV

In my page I am writing the following script to generate CSV to download.
My string 'str' has some new line char's "\n" but generated csv is all in one line. am I missing anything?

var fileContent = "data:text/csv;charset=utf-8," + str;
var a = document.createElement('a');
a.href = fileContent; = filename;
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);


you need to convert the data to base64

in most browsers, it's as simple as

var fileContent = "data:text/csv;charset=utf-8;base64," + btoa(str);

However, if you have a Unicode string, this will fail. Consider this instead - source =

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent(str)));
var fileContent = "data:text/csv;charset=utf-8;base64," + utf8_to_b64(str);