To correctly handle the case where the card name contains commas (like "Surrak, Elusive Hunter"), you need to modify your code to properly parse the CSV line. The current approach of simply splitting on commas will incorrectly split the name into multiple parts.
Here's the corrected code:
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line) {
// Split the line properly accounting for quoted fields
const columns = [];
let current = '';
let inQuotes = false;
for (const char of line) {
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
columns.push(current);
current = '';
} else {
current += char;
}
}
columns.push(current); // Add the last field
// Clean up the columns by removing quotes and trimming whitespace
const cleanedColumns = columns.map(col => col.replace(/"/g, '').trim());
if (cleanedColumns.length >= 3) {
const id = cleanedColumns[0];
const name = cleanedColumns[2];
cardMap.set(id, name);
}
}
}
This solution:
- Properly handles quoted fields by tracking when we're inside quotes
- Only splits on commas that are outside of quoted sections
- Cleans up the fields by removing quotes and trimming whitespace
- Still maintains the same basic structure of your original code
For the input line 96493,TDM,"Surrak, Elusive Hunter",rare,G,3,Legendary Creature - Human Warrior,False, this will correctly:
- Parse the ID as "96493"
- Parse the name as "Surrak, Elusive Hunter" (with the comma preserved)
- Store it in the cardMap as expected
Alternative approach: If you're working in a Node.js environment or can use external libraries, you might want to consider using a proper CSV parsing library like csv-parser or papaparse which would handle these edge cases automatically.