Files and data

Parse a small quoted CSV record

A CSV parser needs to distinguish commas inside quotes from actual field separators. A small state machine can demonstrate the rule, while a maintained parser is preferable for general imports.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function parseRecord(text) {
  const fields = []; let field = "", quoted = false, closed = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"' && text[i + 1] === '"') { field += '"'; i++; }
      else if (c === '"') { quoted = false; closed = true; }
      else field += c;
    } else if (c === ',') { fields.push(field); field = ""; closed = false; }
    else if (closed) throw new Error("Unexpected text after closing quote");
    else if (c === '"') { if (field) throw new Error("Unexpected quote"); quoted = true; }
    else if (c === '\r' || c === '\n') throw new Error("Expected one record");
    else field += c;
  }
  if (quoted) throw new Error("Unclosed quote");
  return [...fields, field];
}
console.log(JSON.stringify(parseRecord('one,"two, three","a ""quote"""')));

How it works

The quoted state treats commas as content and pairs doubled quotes into a literal quote. Outside quotes, commas finish fields. Tracking a closed quoted field lets the example reject text appended after its closing quote instead of silently accepting malformed input.

Limits and mistakes

This educational function handles one record and deliberately rejects external line terminators. It is not a streaming CSV-file parser with encoding detection or dialect negotiation. Use maintained tooling for arbitrary files and enforce size limits.

Check the result

Expect ["one","two, three","a "quote""]. Test empty fields, a final comma, doubled quotes, and an unclosed quote before adapting the state machine.

Sources

Reference documentation for the behavior used in this guide: