This commit is contained in:
23
02_advanced/uebungen/u26_csv-quotes2/index.js
Normal file
23
02_advanced/uebungen/u26_csv-quotes2/index.js
Normal file
@@ -0,0 +1,23 @@
|
||||
// Übung 26: CSV-Datensätze mit Anführungszeichen — Teil 2
|
||||
// In der Praxis finden sich auch CSV-Datensätze, in denen manche Felder mit Anführungszeichen umgeben sind und manche nicht.
|
||||
|
||||
// Schreibe ein Programm, das auch mit diesen Fällen zurechtkommt. Folgender Datensatz soll korrekt zerlegt werden:
|
||||
|
||||
const mixedCSV = '"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
|
||||
const regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g;
|
||||
|
||||
const matches = [...mixedCSV.matchAll(regex)];
|
||||
|
||||
const result = matches.map((match) => {
|
||||
// Wenn Gruppe 1 existiert, war es ein String in Anführungszeichen
|
||||
// Wenn Gruppe 2 existiert, war es ein unberührter Wert (Zahl)
|
||||
const value = match[1] !== undefined ? match[1] : match[2].trim();
|
||||
|
||||
// Optional: Datentypen konvertieren
|
||||
if (!isNaN(value) && value !== '') {
|
||||
return Number(value);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
console.log(result);
|
||||
Reference in New Issue
Block a user