Created
November 13, 2025 13:57
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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