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

snippet
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;
}