Extract ISO dates and Spanish dates
Before handing text to a model, pull the dates out with a regular expression and drop the ones that do not exist.
Write extractDates(text). Return an array of the dates in the text as ISO YYYY-MM-DD, in the order they appear. Recognise two forms:
- ISO:
2026-09-28; - Spanish:
4 de octubre de 2026, case-insensitive (1 de Diciembre de 2026). The day may have one or two digits; the output always uses two (2026-10-04).
Drop impossible dates such as 2026-02-31 or 29 de febrero de 2025 (2025 is not a leap year). TEXT already holds an example.
Challenges 0/5
- Pulls the three valid dates from the example, in order
- Converts Spanish dates with a two-digit day
- Drops impossible dates
- Accepts 29 February in a leap year
- Text without dates returns an empty array
function extractDates(text) {
const out = [];
// 1. one regex with two alternatives: YYYY-MM-DD and "D de mes de YYYY" (flags gi)
// 2. turn each match into year, month, day
// 3. keep it only if it is a real date, formatted as YYYY-MM-DD
for (const m of text.matchAll(/(\d{4})-(\d{2})-(\d{2})/g)) out.push(m[0]);
return out;
}
console.log(extractDates(TEXT));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
Dates are the data a small model handles worst: it swaps day and month, makes up the year or accepts a 31 February. A regular expression pulls them out in microseconds, the same way every time, and checking that the date exists is one line. The rule this exercise leaves applies to the whole track: anything with a fixed format is extracted with code, and the model is left with what needs reading. In Ollama structured output: 40 invoices measured we saw a 7B model read the date of a receipt with the month first.
Go deeper: the MDN reference →
This in production, with your data? Let's talk for 15 minutes →