Files and data

Escape fields when writing CSV

Quote a CSV field when it contains a comma, quote, or line break, and double embedded quotes inside quoted fields. Joining raw values with commas cannot represent those values reliably.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function csvField(value) {
  const text = String(value);
  return /[",\r\n]/.test(text) ? '"' + text.replaceAll('"', '""') + '"' : text;
}
const row = ["plain", "last, first", 'a "quote"'];
console.log(row.map(csvField).join(","));

How it works

Each field is escaped independently before separators are inserted. The second field needs quotes because its comma is data, and the third doubles its embedded quotation marks. A complete document can join rows with CRLF under the common CSV convention.

Limits and mistakes

CSV quoting protects field boundaries, not spreadsheet formula execution. Null, undefined, dates, and decimal conventions still need an explicit export policy. For complex compatibility requirements, use a well-tested CSV library.

Check the result

Expect plain,"last, first","a ""quote""". Round-trip commas, quotes, and embedded newlines through a proper CSV parser before using this helper for important exports.

Sources

Reference documentation for the behavior used in this guide: