CSV Row Parser With Quoted Fields
Parse one CSV row with a configurable delimiter, quoted fields, doubled quotes and strict errors for malformed input.
Code
export function parseCsvRow(line, delimiter = ",") {
if (typeof line !== "string") throw new TypeError("line must be a string");
if (typeof delimiter !== "string" || delimiter.length !== 1) {
throw new RangeError("delimiter must be a single character");
}
const fields = [];
let field = "";
let quoted = false;
for (let index = 0; index < line.length; index += 1) {
const char = line[index];
if (quoted) {
if (char === '"') {
if (line[index + 1] === '"') {
field += '"';
index += 1;
} else {
quoted = false;
}
} else {
field += char;
}
} else if (char === delimiter) {
fields.push(field);
field = "";
} else if (char === '"' && field === "") {
quoted = true;
} else {
field += char;
}
}
if (quoted) throw new RangeError("unterminated quoted field");
fields.push(field);
return fields;
}How the snippet works
One way to read it: the function parseCsvRow, doing all the work.
Iteration happens inside for (let index = 0; index < line.length; index += 1) — everything outside it runs once. Failure is loud: TypeError and RangeError aborts the current operation instead of degrading it.
Points of care
- The guard
typeof line !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export function parseCsvRow(line, delimiter = ",")
Import parseCsvRow from the file and call it — the rest of the code is implementation detail.
Statements that matter
if (typeof line !== "string") throw new TypeError("line must be a string");
if (quoted) throw new RangeError("unterminated quoted field");
throw new RangeError("delimiter must be a single character");
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
- How does the snippet fail?
- The code throws `TypeError` and `RangeError` — the guard `typeof line !== "string"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `parseCsvRow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.