Dwix
Dwix

Reputation: 1257

Line break after the last item in the array in Javascript

I have this code which allows me to download a CSV file using two dimensional array, but I need to have a line break just after the last item in first array. ( just after some other info.

<script type="text/javascript">

    // Example data given in question text
    var data = [
        ['name1', 'city1', 'some other info'],
        ['name2', 'city2', 'more info']
    ];

    // Building the CSV from the Data two-dimensional array
    // Each column is separated by ";" and new line "\n" for next row
    var csvContent = '';
    data.forEach(function(infoArray, index) {
        dataString = infoArray.join(';');
        csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    // The download function takes a CSV string, the filename and mimeType as parameters
    // Scroll/look down at the bottom of this snippet to see how download is called
    var download = function(content, fileName, mimeType) {
        var a = document.createElement('a');
        mimeType = mimeType || 'application/octet-stream';

        if (navigator.msSaveBlob) { // IE10
            navigator.msSaveBlob(new Blob([content], {
                type: mimeType
            }), fileName);
        } else if (URL && 'download' in a) { //html5 A[download]
            a.href = URL.createObjectURL(new Blob([content], {
                type: mimeType
            }));
            a.setAttribute('download', fileName);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        } else {
            location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
        }
    }

    download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');
</script>

So to be clear, the result that I get now is :

name1;city1;some other infoname2;city2;more info

and I need it to be :

name1;city1;some other info
name2;city2;more info

Thanks a ton in advance.

Upvotes: 0

Views: 62

Answers (1)

glennsl
glennsl

Reputation: 29106

It might be that whatever you are using to display the file expects Windows line endings instead of UNIX line endings. Try \r\n instead of just \n.

Upvotes: 1

Related Questions