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;
}How it works
Parse a CSV Line With Quoted Fields keeps everything in the function parseCsvLine.
Iteration happens inside for (let i = 0; i < line.length; i++) — everything outside it runs once.
Using it
The main signature reads export function parseCsvLine(line)
parseCsvLine is the public entry point; everything else in the file exists to support it.
Key statements
current += char;
current += '"';
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `parseCsvLine` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.