Extract a date from a string with regex in JavaScript
Intermediate · 3 min read
Dates hide inside all kinds of text: booking emails, log files, chat messages, notes. "Departs 2025-03-14 from Ojota, returns 2025-03-21" has two of them. In this tutorial you will pull every date out of a sentence like that with a regular expression, then check each one is a day that really exists.
That second part is the one most tutorials skip. A pattern happily accepts 2025-02-30, a day that never happens. You will see why, and how to catch it in three lines. You need to know /.../, \d and arrays. Named groups and matchAll are explained as we go.
The shape of a date
The dates here are written year, month, day: 2025-03-14. In pattern terms that is four digits, a dash, two digits, a dash, two digits. \d{4} means "exactly four digits":
console.log(/\d{4}-\d{2}-\d{2}/.test('Departs 2025-03-14')); // true
console.log(/\d{4}-\d{2}-\d{2}/.test('Departs soon')); // false
There is no ^ or $ this time, because the date sits in the middle of other text.
Capture groups
Brackets in a pattern capture the text they match, so you can read it afterwards. Give a group a name with ?<name> right after the opening bracket, and the match keeps the parts under groups:
const m = '2025-03-14'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year); // '2025'
console.log(m.groups.month); // '03'
console.log(m.groups.day); // '14'
Named groups read better than numbered ones like m[1], and they don't shift if you add a group later.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
4 Find a date inside a string
fairPull a date out of surrounding text. Then check it is a date that exists, which a pattern cannot do.
Stuck? Three hints, smallest first
- 1. Named groups,
(?<year>\d{4}), read far better thanmatch[1]. - 2. Use the
gflag withmatchAllto find every date, not just the first. - 3.
new Date(2025, 1, 30)silently becomes 2 March. Check the parts survived.
Step 1: match only finds the first date
Try match on a sentence with two dates:
const text = 'Departs 2025-03-14, returns 2025-03-21.';
const DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
console.log(text.match(DATE)[0]); // '2025-03-14': the return date is ignored
Without the g flag, a pattern stops at its first match. To find all of them we need two changes.
Step 2: the g flag and matchAll
Add g (for "global") after the closing slash, and use matchAll. It gives back every match, each with its own groups and its position in the text, index. Spreading it with [...] turns the results into an ordinary array:
const DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
const text = 'Departs 2025-03-14 from Ojota, returns 2025-03-21. Booked on 2024-12-01.';
const found = [...text.matchAll(DATE)];
console.log(found.length); // 3
console.log(found[1][0]); // '2025-03-21'
console.log(found[0].index); // 8
console.log(found[2].groups.year); // '2024'
found[1][0] is the whole text of the second match. index 8 means the first date starts at the ninth character, because counting starts at 0.
Step 3: return tidy objects
map turns each match into a plain object. The spread ...m.groups copies year, month and day into it:
const DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
function findDates(text) {
return [...text.matchAll(DATE)].map((m) => ({
text: m[0],
index: m.index,
...m.groups,
}));
}
const first = findDates('Departs 2025-03-14 from Ojota')[0];
console.log(first.text, first.day); // 2025-03-14 14
console.log(findDates('no dates here').length); // 0
The parts are strings, not numbers. Convert them with Number when you need to do math.
Step 4: a pattern can't count days
Now the catch. Each of these has the right shape:
const shape = /^\d{4}-\d{2}-\d{2}$/;
console.log(shape.test('2025-02-30')); // true, but February has no 30th
console.log(shape.test('2025-13-01')); // true, but there is no month 13
JavaScript's Date won't complain either. It quietly rolls over into the next month. Date.UTC builds the date in UTC so your time zone can't change the result, and months count from 0, so February is 1:
const d = new Date(Date.UTC(2025, 1, 30));
console.log(d.toISOString().slice(0, 10)); // '2025-03-02'
Step 5: check nothing rolled over
That rollover is the test. Build the date, then read the year, month and day back. If any of them changed, the input was never a real date:
function isRealDate(year, month, day) {
const y = Number(year);
const m = Number(month);
const d = Number(day);
const date = new Date(Date.UTC(y, m - 1, d));
return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
}
console.log(isRealDate('2025', '03', '14')); // true
console.log(isRealDate('2025', '02', '30')); // false
console.log(isRealDate('2024', '02', '29')); // true: 2024 is a leap year
console.log(isRealDate('2025', '02', '29')); // false
Leap years come for free, because Date already knows them.
The full solution
The panel finds the three dates in the booking sentence, then runs five candidates through both the pattern and the real-date check. Press Run to see which ones the pattern wrongly accepts.
// Named groups, so the result reads as words rather than numbers.
const DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
function findDates(text) {
return [...text.matchAll(DATE)].map((m) => ({
text: m[0],
index: m.index,
...m.groups,
}));
}
/* A pattern accepts 2025-02-30. The only reliable existence check is to build
the date and confirm nothing was rolled over. */
function isRealDate(year, month, day) {
const y = Number(year);
const m = Number(month);
const d = Number(day);
const date = new Date(Date.UTC(y, m - 1, d));
return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
}
const text = 'Departs 2025-03-14 from Ojota, returns 2025-03-21. Booked on 2024-12-01.';
console.log('found:', findDates(text).map((d) => d.text));
console.log('first :', findDates(text)[0]);
console.log('--- a pattern cannot tell a real date from an impossible one ---');
for (const candidate of ['2025-02-30', '2025-13-01', '2024-02-29', '2025-02-29', '2025-04-31']) {
const [y, m, d] = candidate.split('-');
console.log(candidate, 'matches the pattern:', /^\d{4}-\d{2}-\d{2}$/.test(candidate), '| is a real date:', isRealDate(y, m, d));
}
console.log('what Date does with 2025-02-30:', new Date(Date.UTC(2025, 1, 30)).toISOString().slice(0, 10), '<- rolled over');
Output
17 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 17 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every date in the text is found', findDates(text).length, 3);
test('the first one', findDates(text)[0].text, '2025-03-14');
test('its parts are named', findDates(text)[0].year, '2025');
test('and the month', findDates(text)[0].month, '03');
test('and the day', findDates(text)[0].day, '14');
test('the position is reported', findDates(text)[0].index, 8);
test('the last one is found too', findDates(text).at(-1).text, '2024-12-01');
test('text with no date gives nothing', findDates('no dates here'), []);
test('the parts are strings, not numbers', typeof findDates(text)[0].day, 'string');
test('30 February matches the pattern', /^\d{4}-\d{2}-\d{2}$/.test('2025-02-30'), true);
test('but is not a real date', isRealDate('2025', '02', '30'), false);
test('month 13 is not either', isRealDate('2025', '13', '01'), false);
test('31 April is not', isRealDate('2025', '04', '31'), false);
test('29 February exists in a leap year', isRealDate('2024', '02', '29'), true);
test('and does not in a normal one', isRealDate('2025', '02', '29'), false);
test('a real date passes both checks', isRealDate('2025', '03', '14'), true);
test('Date rolls an impossible day into the next month', new Date(Date.UTC(2025, 1, 30)).getUTCMonth(), 2);
Named capture groups turn match[1], match[2], match[3] into groups.year, groups.month, groups.day. It costs nothing and removes a whole class of off-by-one mistake, especially once a pattern gains a group in the middle and every later number shifts.
The substance is the second half. 2025-02-30 matches any date pattern you can write, and new Date(Date.UTC(2025, 1, 30)) does not complain — it silently becomes 2 March, which the last assertion confirms. So the existence check is: build the date, then verify the year, month and day that come back are the ones you put in. If they differ, the input rolled over and was never a real date. This is the only reliable way, and it handles leap years for free — the assertions check 29 February in both 2024 and 2025.
Common mistakes
- Forgetting the
gflag.matchAllthrows aTypeErrorif the pattern has nog, andmatchwithout it only returns the first date. - Using months from 1 in
Date.Date.UTC(2025, 3, 14)is 14 April, not March. Subtract 1 from the month. - Trusting the pattern for validity.
\d{2}accepts 00 to 99 for both month and day. Always check the date exists.
Try it yourself
- Change the pattern to find dates written
14/03/2025(day, month, year). - Make
findDateskeep only the real ones by adding.filter((d) => isRealDate(d.year, d.month, d.day)). - Sort the found dates from earliest to latest. (Hint:
YYYY-MM-DDstrings sort correctly as text.)