I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8
and have all the attribute info in array, which loo
I use this function to convert an string[][]
to a csv file. It quotes a cell, if it contains a "
, a ,
or other whitespace (except blanks):
/**
* Takes an array of arrays and returns a `,` sparated csv file.
* @param {string[][]} table
* @returns {string}
*/
function toCSV(table) {
return table
.map(function(row) {
return row
.map(function(cell) {
// We remove blanks and check if the column contains
// other whitespace,`,` or `"`.
// In that case, we need to quote the column.
if (cell.replace(/ /g, '').match(/[\s,"]/)) {
return '"' + cell.replace(/"/g, '""') + '"';
}
return cell;
})
.join(',');
})
.join('\n'); // or '\r\n' for windows
}
Note: does not work on Internet Explorer < 11 unless map
is polyfilled.
Note: If the cells contain numbers, you can add cell=''+cell
before if (cell.replace...
to convert numbers to strings.
Or you can write it in one line using ES6:
t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')