Understanding the RFC 4180 CSV Specification
- • Comma-Separated Values (CSV) is standardized by IETF RFC 4180. Key requirements include:
- • Delimiters: Fields are separated by commas (or semicolons in European locales).
- • Quoting Rules: Any field containing commas, line breaks (CRLF), or double quotes must be wrapped in double quotes.
- • Escaping Quotes: A literal double quote inside a quoted field is escaped by doubling it ("").
- • UTF-8 BOM: Prepending a Byte Order Mark (\uFEFF) ensures Microsoft Excel properly renders non-ASCII Unicode characters (accents, Asian scripts, emojis).
// RFC 4180 Compliant CSV Line Escaping in TypeScript
export function escapeCsvField(val: unknown): string {
if (val === null || val === undefined) return '';
const str = typeof val === 'object' ? JSON.stringify(val) : String(val);
if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}