🔐Encoding & Escaping
CSV Field Escaping
Properly escape commas, quotes, and newlines in CSV data
Explanation
CSV fields containing commas, quotes, or newlines must be quoted and quotes must be doubled.
Examples
Field with comma
Input
Smith, John
Output
"Smith, John"
Field with quote
Input
He said "Hello"
Output
"He said ""Hello"""
Field with newline
Input
Line 1\nLine 2
Output
"Line 1\nLine 2"
Code Examples
JavaScript
// Escape CSV field
function escapeCsvField(field) {
// Convert to string
field = String(field);
// If contains comma, quote, or newline, quote it
if (field.includes(',') || field.includes('"') || field.includes('\n')) {
// Double any existing quotes
field = field.replace(/"/g, '""');
// Wrap in quotes
return `"${field}"`;
}
return field;
}
// Generate CSV row
function generateCsvRow(values) {
return values.map(escapeCsvField).join(',');
}
// Generate complete CSV
function generateCsv(data, headers) {
const rows = [
generateCsvRow(headers),
...data.map(row => generateCsvRow(
headers.map(h => row[h] ?? '')
))
];
return rows.join('\n');
}
// Usage
const data = [
{ name: 'Smith, John', quote: 'He said "Hello"', age: 30 },
{ name: 'Doe, Jane', quote: 'Simple text', age: 25 }
];
const csv = generateCsv(data, ['name', 'quote', 'age']);
console.log(csv);
// name,quote,age
// "Smith, John","He said ""Hello""",30
// "Doe, Jane",Simple text,25
// Parse CSV (basic)
function parseCsvRow(row) {
const values = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < row.length; i++) {
const char = row[i];
const next = row[i + 1];
if (char === '"' && inQuotes && next === '"') {
current += '"';
i++; // Skip next quote
} else if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
values.push(current);
current = '';
} else {
current += char;
}
}
values.push(current);
return values;
}
// Better: Use a library
// npm install papaparse
import Papa from 'papaparse';
const csv = Papa.unparse(data);
const parsed = Papa.parse(csv, { header: true }); Python
import csv
import io
# Escape CSV field (manual)
def escape_csv_field(field):
field = str(field)
if ',' in field or '"' in field or '\n' in field:
field = field.replace('"', '""')
return f'"{field}"'
return field
# Write CSV (recommended way)
def write_csv(data, headers):
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=headers)
writer.writeheader()
writer.writerows(data)
return output.getvalue()
# Usage
data = [
{'name': 'Smith, John', 'quote': 'He said "Hello"', 'age': 30},
{'name': 'Doe, Jane', 'quote': 'Simple text', 'age': 25}
]
csv_content = write_csv(data, ['name', 'quote', 'age'])
print(csv_content)
# Read CSV
def read_csv(csv_string):
input_stream = io.StringIO(csv_string)
reader = csv.DictReader(input_stream)
return list(reader)
# Custom delimiter/quoting
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(
f,
delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL # Only quote when needed
)
writer.writerow(['Name', 'Quote', 'Age'])
writer.writerow(['Smith, John', 'He said "Hello"', 30])Try it Now
💡 Tips
- Use CSV library instead of manual escaping
- Quote fields with comma, quote, or newline
- Double quotes inside quoted fields (" → "")
- Use QUOTE_MINIMAL to quote only when needed
- Consistent line endings (\n or \r\n)
- UTF-8 with BOM for Excel compatibility
- Escape formulas (=, +, -, @) to prevent injection
- Test with special characters and edge cases
⚠️ Common Pitfalls
- Forgetting to escape quotes causes parse errors
- Not quoting fields with commas
- Inconsistent quoting strategy
- Excel formula injection via =, +, -, @
- Character encoding issues (use UTF-8)
- Different line ending conventions
- Unescaped newlines break row parsing