CSV Row Parser With Quoted Fields

Parse one CSV row with a configurable delimiter, quoted fields, doubled quotes and strict errors for malformed input.

JavascriptData Integrity

Code

javascriptsnippet
34 lines
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 early throw when 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

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.