Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created November 13, 2025 13:57
Show Gist options
  • Select an option

  • Save devhammed/c7d70f314a198e018033f3b325d1d721 to your computer and use it in GitHub Desktop.

Select an option

Save devhammed/c7d70f314a198e018033f3b325d1d721 to your computer and use it in GitHub Desktop.
Parse separated string (CSV, TSV, SSV) according to [RFC-4180](https://www.ietf.org/rfc/rfc4180.txt).
function parseSeparated(text: string, delimiter: string = ','): string[][] {
const rows: string[][] = [];
let field = '';
let row: string[] = [];
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const char = text[i];
const next = text[i + 1];
if (char === '"') {
if (inQuotes && next === '"') {
field += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (char === delimiter && !inQuotes) {
row.push(field);
field = '';
} else if ((char === '\n' || char === '\r') && !inQuotes) {
if (char === '\r' && next === '\n') {
i++;
}
row.push(field);
rows.push(row);
field = '';
row = [];
} else {
field += char;
}
}
if (field || row.length > 0) {
row.push(field);
rows.push(row);
}
return rows.filter((r) => r.some((v) => v !== ''));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment