Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active April 16, 2026 21:11
Show Gist options
  • Select an option

  • Save panzi/8bb74b439ea01e745dbdaccfa8cbb043 to your computer and use it in GitHub Desktop.

Select an option

Save panzi/8bb74b439ea01e745dbdaccfa8cbb043 to your computer and use it in GitHub Desktop.
Minimal function to save a CSV from memory in browser JavaScript. Consider this code as public domain, since it's trivial.
export function escapeCSV(value: string): string {
if (/^[-+._=\/a-z0-9]*$/i.test(value)) {
return value;
}
return `"${value.replace(/"/g, '""')}"`;
}
export function buildCSV(data: string[][]): string {
const buf: string[] = ['\ufeff']; // BOM
for (const row of data) {
if (row.length > 0) {
buf.push(escapeCSV(row[0]));
for (let index = 1; index < row.length; ++ index) {
buf.push(',', escapeCSV(row[index]));
}
}
buf.push('\r\n');
}
return buf.join('');
}
export function downloadCSV(filename: string, data: string[][]): void {
const blob = new Blob([buildCSV(data)], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = filename;
link.href = url;
link.style.opacity = '0';
link.style.position = 'fixed';
link.style.right = '0';
link.style.bottom = '0';
document.body.appendChild(link);
link.click();
setTimeout(() => {
URL.revokeObjectURL(url);
link.parentNode?.removeChild(link);
}, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment