Search code examples
javascriptexport-to-csv

Export CSV data with # character in JavaScript does not work


I export JSON data to CSV format and download it with JavaScript. Everything works fine except if the data has the hash sign #. The function does not export all data, for example:

this is my first C# lesson in the academy, it exports only this is my first C and ignore the rest of it.

This is my code

this.handleRow = function (row) {
    var finalVal = '';
    for (var j = 0; j < row.length; j++) {
        var innerValue = "";
        if (row[j]) {
            innerValue = row[j].toString();
        }
        if (row[j] instanceof Date) {
            innerValue = row[j].toLocaleString();
        }
        var result = innerValue.replace(/"/g, '""');
        if (result.search(/("|,|\n)/g) >= 0) {
            result = '"' + result + '"';
        }

        if (j > 0) finalVal += ',';

        finalVal += result;
    }
    return finalVal + '\n';
};

this.jsonToCsv = function (filename, rows) {
    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += this.handleRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;'});
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = $window.document.createElement("a");
        if (typeof link.download === "string") {
            link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvFile));
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            $window.document.body.appendChild(link);
            link.click();
            $window.document.body.removeChild(link);
        }
    }
};

Solution

  • encodeURI encodes characters which are forbidden in a URI, not ones which have special meaning.

    The # won't be encoded but it starts the fragment identifier portion of the URI.

    Use encodeURIComponent instead.