Parse a CSV Line With Quoted Fields
Split a CSV line into fields while respecting quoted values that contain commas or escaped quotes, a step that naive splitting gets wrong.
Code
export function parseCsvLine(line) {
const fields = [];
let current = "";
let quoted = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (quoted) {
if (char === '"') {
if (line[i + 1] === '"') {
current += '"';
i++;
} else {
quoted = false;
}
} else {
current += char;
}
} else if (char === '"') {
quoted = true;
} else if (char === ",") {
fields.push(current);
current = "";
} else {
current += char;
}
}
fields.push(current);
return fields;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.