This commit is contained in:
15
02_advanced/uebungen/u25_csv-quotes/README.md
Normal file
15
02_advanced/uebungen/u25_csv-quotes/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Übung 25: CSV-Datensätze mit Anführungszeichen
|
||||
|
||||
Bisher haben wir die Felder in einem CSV-Datensatz einfach mit der Anweisung:
|
||||
|
||||
```js
|
||||
record.split(',');
|
||||
```
|
||||
|
||||
in einzelne Felder zerlegt. In der Praxis kann es aber vorkommen, dass ein einzelnes Feld ein Komma enthält. Das Problem wird üblicherweise gelöst, indem die einzelnen Felder noch mit Anführungszeichen umgeben werden. Hier ist ein Beispiel:
|
||||
|
||||
```js
|
||||
'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90';
|
||||
```
|
||||
|
||||
Das erste Feld enthält ein Komma (very big, soft computer mouse), trotzdem ist die Unterteilung eindeutig. Schreibe ein kurzes Programm, das diesen Datensatz korrekt zerlegt und die einzelnen Felder ausgibt:
|
||||
14
02_advanced/uebungen/u25_csv-quotes/index.js
Normal file
14
02_advanced/uebungen/u25_csv-quotes/index.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const csvStr = "'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90'";
|
||||
|
||||
console.log(csvStr.slice(1, csvStr.length - 1).split(/', '/));
|
||||
|
||||
// Übung 25: CSV-Datensätze mit Anführungszeichen
|
||||
// Bisher haben wir die Felder in einem CSV-Datensatz einfach mit der Anweisung:
|
||||
|
||||
// record.split(',')
|
||||
|
||||
// in einzelne Felder zerlegt. In der Praxis kann es aber vorkommen, dass ein einzelnes Feld ein Komma enthält. Das Problem wird üblicherweise gelöst, indem die einzelnen Felder noch mit Anführungszeichen umgeben werden. Hier ist ein Beispiel:
|
||||
|
||||
// 'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90'
|
||||
|
||||
// Das erste Feld enthält ein Komma (very big, soft computer mouse), trotzdem ist die Unterteilung eindeutig. Schreibe ein kurzes Programm, das diesen Datensatz korrekt zerlegt und die einzelnen Felder ausgibt:
|
||||
51
02_advanced/uebungen/u26_csv-quotes2/Regex-erklaerung.md
Normal file
51
02_advanced/uebungen/u26_csv-quotes2/Regex-erklaerung.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Regex Beispiel
|
||||
|
||||
Am besten löst man das mit einem regulären Ausdruck, der entweder nach **Inhalten in Anführungszeichen** sucht _oder_ nach **Inhalten ohne Kommas**.
|
||||
|
||||
Hier ist der passende Reguläre Ausdruck:
|
||||
|
||||
`/"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g`
|
||||
|
||||
---
|
||||
|
||||
### Wie der Regex funktioniert
|
||||
|
||||
Der Ausdruck nutzt das **ODER-Prinzip (`|`)**, um zwei Szenarien zu matchen:
|
||||
|
||||
1. **`"([^"\\]*(?:\\.[^"\\]*)*)"` (Gruppe 1):** Matcht alles, was in doppelten Anführungszeichen steht. Er erlaubt sogar escaped Anführungszeichen (`\"`) im Text.
|
||||
2. **`([^,]+)` (Gruppe 2):** Wenn keine Anführungszeichen da sind, matcht er alles bis zum nächsten Komma.
|
||||
|
||||
---
|
||||
|
||||
### Anwendung in JavaScript (Beispiel)
|
||||
|
||||
Da du das Ergebnis sicherlich in einem Array von einzelnen Werten brauchst, kannst du den Regex wie folgt anwenden. Hierbei nutzen wir `matchAll`, um die Treffer sauber zu trennen und die Anführungszeichen direkt zu entfernen:
|
||||
|
||||
```javascript
|
||||
const input = '"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
|
||||
const regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g;
|
||||
|
||||
const matches = [...input.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);
|
||||
```
|
||||
|
||||
### Das Ergebnis (Output)
|
||||
|
||||
Nach dem Parsen erhältst du ein sauberes Array, bei dem die Kommas innerhalb der Strings ignoriert wurden und die Zahlen einsatzbereit sind:
|
||||
|
||||
```json
|
||||
["very big, soft computer mouse", "the cutest peripheral ever", 10, 39.9]
|
||||
```
|
||||
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);
|
||||
@@ -1,31 +1,31 @@
|
||||
"use strict";
|
||||
'use strict';
|
||||
(() => {
|
||||
// dev/assets/js/main.js
|
||||
(() => {
|
||||
const DOM = {
|
||||
weatherBox: document.querySelector(".weather-box"),
|
||||
weatherIcon: document.querySelector(".weather-pic img"),
|
||||
figcaption: document.querySelector("figcaption"),
|
||||
description: document.querySelector(".description"),
|
||||
temp: document.querySelector(".temp"),
|
||||
tempMin: document.querySelector(".temp-min"),
|
||||
tempMax: document.querySelector(".temp-max"),
|
||||
windIcon: document.querySelector(".wind-icon"),
|
||||
speed: document.querySelector(".speed"),
|
||||
deg: document.querySelector(".deg")
|
||||
weatherBox: document.querySelector('.weather-box'),
|
||||
weatherIcon: document.querySelector('.weather-pic img'),
|
||||
figcaption: document.querySelector('figcaption'),
|
||||
description: document.querySelector('.description'),
|
||||
temp: document.querySelector('.temp'),
|
||||
tempMin: document.querySelector('.temp-min'),
|
||||
tempMax: document.querySelector('.temp-max'),
|
||||
windIcon: document.querySelector('.wind-icon'),
|
||||
speed: document.querySelector('.speed'),
|
||||
deg: document.querySelector('.deg'),
|
||||
};
|
||||
console.log(DOM);
|
||||
const API_KEY = "";
|
||||
const API_KEY = '';
|
||||
const LAT = 43.72072300281546;
|
||||
const LON = 7.352450291796612;
|
||||
const TEMP_MAX_ALERT_AMOUNT = 30;
|
||||
const TEMP_MIN_ALERT_AMOUNT = 10;
|
||||
const init = () => {
|
||||
console.log("init!");
|
||||
console.log('init!');
|
||||
getWeather().then((data) => {
|
||||
console.log(data);
|
||||
if (data) {
|
||||
DOM.weatherBox.classList.add("show", "animate__flipInX");
|
||||
DOM.weatherBox.classList.add('show', 'animate__flipInX');
|
||||
setWeather(data);
|
||||
}
|
||||
});
|
||||
@@ -33,9 +33,9 @@
|
||||
const getWeather = async () => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`https://api.openweathermap.org/data/2.5/weather?lat=${LAT}&lon=${LON}&units=metric&appid=${API_KEY}`
|
||||
`https://api.openweathermap.org/data/2.5/weather?lat=${LAT}&lon=${LON}&units=metric&appid=${API_KEY}`,
|
||||
);
|
||||
if (!res.ok) throw new Error("Fetch Error");
|
||||
if (!res.ok) throw new Error('Fetch Error');
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
@@ -57,9 +57,9 @@
|
||||
DOM.weatherIcon.src = `https://openweathermap.org/img/wn/${icon}@2x.png`;
|
||||
DOM.windIcon.style.transform = `rotate(${Number(deg) - 45}deg)`;
|
||||
if (Number(temp) >= TEMP_MAX_ALERT_AMOUNT) {
|
||||
DOM.temp.classList.add("danger");
|
||||
DOM.temp.classList.add('danger');
|
||||
} else if (Number(temp) <= TEMP_MIN_ALERT_AMOUNT) {
|
||||
DOM.temp.classList.add("frozen");
|
||||
DOM.temp.classList.add('frozen');
|
||||
}
|
||||
};
|
||||
init();
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
console.log(DOM);
|
||||
|
||||
// BITTE EIGENEN API KEY VERWENDEN
|
||||
// (NICHT DIESEN KEY VERWENDEN: b62eaccfd1a09cf1d04b00bd2ec689e7)
|
||||
const API_KEY = '';
|
||||
const LAT = 43.72072300281546;
|
||||
const LON = 7.352450291796612;
|
||||
|
||||
Reference in New Issue
Block a user