Simply joining values with commas fails if values contain commas, double quotes, or newlines. To comply with RFC-4180 specifications, cells containing special characters must be wrapped in double quotes, and any inner double quotes must be escaped by doubling them (
""). When writing guides or technical articles about this, you can convert them with our
Markdown to HTML Converter. Here is a standard ES6 formatter for CSV cells:
function escapeCsvCell(value, delimiter = ",") {
if (value === null || value === undefined) return "";
let str = typeof value === "object" ? JSON.stringify(value) : String(value);
const needsQuotes =
str.includes(delimiter) ||
str.includes('"') ||
str.includes("\n") ||
str.includes("\r");
if (needsQuotes) {
str = str.replace(/"/g, '""');
return `"${str}"`;
}
return str;
}