CSV Field Escaping for Safe Export

Escape CSV fields containing delimiters, quotes, line breaks or edge whitespace, doubling quotes and leaving simple values alone.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
export function escapeCsvField(value: unknown, delimiter = ","): string {
  if (typeof delimiter !== "string" || delimiter.length !== 1) {
    throw new RangeError("delimiter must be a single character");
  }
  if (value === null || value === undefined) return "";
  const text = String(value);
  const needsQuotes =
    text.includes(delimiter) ||
    text.includes('"') ||
    /[\r\n]/.test(text) ||
    /^\s|\s$/.test(text);
  if (!needsQuotes) return text;
  return '"' + text.replace(/"/g, '""') + '"';
}

export function toCsvRow(values: readonly unknown[], delimiter = ","): string {
  return values.map((value) => escapeCsvField(value, delimiter)).join(delimiter);
}

How the snippet works

CSV Field Escaping for Safe Export is built around the functions escapeCsvField and toCsvRow.

Failure is loud: RangeError aborts the current operation instead of degrading it.

What to watch for

  • The guard typeof delimiter !== "string" || delimiter.length !== 1 short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads export function escapeCsvField(value: unknown, delimiter = ",")

The surface worth importing is escapeCsvField; the helpers around it are private to the snippet.

Key statements

return values.map((value) => escapeCsvField(value, delimiter)).join(delimiter);
throw new RangeError("delimiter must be a single character");
if (value === null || value === undefined) return "";

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
The code refuses to continue: `RangeError` is thrown while the state is still recoverable.
Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `escapeCsvField`, `toCsvRow` at load time.