All articles

How to parse CSV in JavaScript

· 2 min read

CSV looks like the simplest data format there is, so most parsers start as text.split("\n").map((line) => line.split(",")). It works on the first test file and fails on the first real one. This guide explains the rules that break it and shows how to parse CSV correctly.

Why split() fails

id,name,notes
1,"Smith, Jane","Said ""hello"""
2,Ravi,"Line one
line two"

This file has three columns and two records. Splitting on line breaks and commas gives you four lines and rows with four or five columns, quotes still attached.

The rules (RFC 4180)

RFC 4180 describes the format most tools produce:

  1. Records are separated by line breaks (\r\n, though \n is common).
  2. Fields are separated by the delimiter, usually a comma.
  3. A field containing the delimiter, a quote or a line break is enclosed in double quotes.
  4. A quote inside a quoted field is written twice: "".
  5. The first record may be a header.

In practice you'll also meet semicolons or tabs as delimiters, a byte order mark at the start, and trailing empty lines.

A small correct parser

This state machine handles quoted fields, doubled quotes and line breaks inside quotes:

function parseCsv(text, delimiter = ",") {
  text = text.replace(/^\uFEFF/, "");
  const rows = [];
  let row = [], field = "", inQuotes = false;

  for (let i = 0; i < text.length; i++) {
    const ch = text[i];
    if (inQuotes) {
      if (ch === '"' && text[i + 1] === '"') { field += '"'; i++; }
      else if (ch === '"') inQuotes = false;
      else field += ch;
    } else if (ch === '"') {
      inQuotes = true;
    } else if (ch === delimiter) {
      row.push(field); field = "";
    } else if (ch === "\n" || ch === "\r") {
      if (ch === "\r" && text[i + 1] === "\n") i++;
      row.push(field); rows.push(row);
      row = []; field = "";
    } else {
      field += ch;
    }
  }
  if (field !== "" || row.length) { row.push(field); rows.push(row); }
  if (inQuotes) throw new Error("Unclosed quoted field");
  return rows;
}

Turning rows into objects with the header:

function csvToObjects(text) {
  const [header, ...rows] = parseCsv(text);
  return rows.map((row) => Object.fromEntries(header.map((key, i) => [key, row[i] ?? ""])));
}

csvToObjects('id,name\n1,"Smith, Jane"\n2,Ravi');
// [ { id: '1', name: 'Smith, Jane' }, { id: '2', name: 'Ravi' } ]

Use a library for production

For user uploads and large files, a maintained library handles more edge cases and performance:

import Papa from "papaparse";

const { data, errors, meta } = Papa.parse(text, {
  header: true,
  skipEmptyLines: true,
  dynamicTyping: true,   // "42" → 42, "true" → true
});

Papa Parse works in browsers and Node.js, detects the delimiter, reports row-level errors, and can stream large files or parse them in a worker. In Node.js, csv-parse from the csv project is another solid choice, with a streaming API.

Reading a file in the browser

input.addEventListener("change", async () => {
  const text = await input.files[0].text();   // decodes as UTF-8
  const records = csvToObjects(text);
});

File.text() always decodes UTF-8. Files exported from older Excel versions may be in Windows-1252; decode those with new TextDecoder("windows-1252").decode(await file.arrayBuffer()).

Types: everything is a string

CSV has no types. "007", "1e5", "TRUE" and "2026-10-22" are all just text, and converting them blindly causes bugs:

  • Leading zeros disappear when "007" becomes 7, which breaks ZIP codes, phone numbers and IDs.
  • Large IDs lose precision above 2^53 when converted to numbers.
  • Dates have no standard format; 03/04/2026 is March or April depending on the locale.

Convert per column, based on what the column means:

const toNumber = (v) => (v === "" ? null : Number(v));
const records = csvToObjects(text).map((r) => ({ ...r, price: toNumber(r.price), quantity: toNumber(r.quantity) }));

Large files

Reading a 500 MB file into one string will crash a browser tab. Stream it instead:

Papa.parse(file, {
  header: true,
  worker: true,                    // parse off the main thread
  step: (result) => handleRow(result.data),
  complete: () => console.log("done"),
});

In Node.js, pipe a file stream through csv-parse and process records as they arrive.

Validate before you trust it

  • Check that the header has the columns you expect.
  • Check that every row has the same number of fields; a mismatch often means a broken quote.
  • Report errors with row numbers, so the person who uploaded the file can fix it.

If you need to go the other way, converting JSON to CSV covers quoting, nested objects and formula injection. And once the data is JSON, validating it catches structural problems early.

Frequently asked questions

Why does the first column name have a strange character?

The file starts with a UTF-8 byte order mark (\uFEFF), which Excel adds. Strip it: text.replace(/^\uFEFF/, "").

Should empty cells become null or empty strings?

CSV can't tell them apart. Decide per column: empty strings for text, null for numbers and dates is a common choice.

How do I parse a CSV with semicolons?

Set the delimiter explicitly, or detect it by checking which candidate splits the first rows into the same number of fields. European Excel exports often use semicolons.

Can I parse CSV with a regex?

Only for simple cases. Quoted fields with line breaks need a parser that tracks state across lines.

Further reading