CSV Field Escaping for Safe Export
Escape CSV fields containing delimiters, quotes, line breaks or edge whitespace, doubling quotes and leaving simple values alone.
Code
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 !== 1short-circuits the flow with an earlythrowwhen 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
Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.