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.

JavascriptData Integrity

Code

javascriptsnippet
29 lines
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

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.