export const parseCsvText = (text: string, delimiter: string) => {
const normalized = text.replace(/^\uFEFF/, "");
const rows: string[][] = [];
let row: string[] = [];
let field = "";
let inQuotes = false;
for (let i = 0; i < normalized.length; i += 1) {
const char = normalized[i];
if (char === '"') {
if (inQuotes && normalized[i + 1] === '"') {
field += '"';
i += 1;
continue;
}
inQuotes = !inQuotes;
continue;
}
if (!inQuotes && char === delimiter) {
row.push(field);
field = "";
continue;
}
if (!inQuotes && (char === "\n" || char === "\r")) {
if (char === "\r" && normalized[i + 1] === "\n") {
i += 1;
}
row.push(field);
rows.push(row);
row = [];
field = "";
continue;
}
field += char;
}
if (field.length > 0 || row.length > 0) {
row.push(field);
rows.push(row);
}
return rows;
};
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter