CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Date Formats in JavaScript - implementing Variations

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
regex javascript node.js JavaScript

I'm integrating two systems and I'm trying to extract dates from a string that can have various formats, such as '2023-10-15', '15/10/2023', and 'October 15, 2023'. However, my current regex only captures the first format and misses the others. Here's the regex I've written: ```javascript const regex = /\b(\d{4}-\d{2}-\d{2})\b/; // Matches YYYY-MM-DD const testString = 'Important dates are 2023-10-15, 15/10/2023, and October 15, 2023.'; const matches = testString.match(regex); console.log(matches); ``` This code only returns `2023-10-15`, which is expected, but when I try to include other formats like this: ```javascript const regex = /\b(\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}\/\d{4}|[A-Za-z]+ \d{1,2}, \d{4})\b/; ``` I get an unexpected result, where it captures only the first date format still. I even tried to use the `g` flag to capture all occurrences, but I ended up with `null` if I included the other formats in a single `match()` call. When testing with this updated regex: ```javascript const testString = 'Important dates are 2023-10-15, 15/10/2023, and October 15, 2023.'; const regex = /\b(\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}\/\d{4}|[A-Za-z]+ \d{1,2}, \d{4})\b/g; const matches = testString.match(regex); console.log(matches); ``` I receive `['2023-10-15']` only. What am I missing? Is there a specific syntax scenario or a better approach to handle multiple date formats? I'm using Node.js version 16.13.0 and regex101 shows all formats working correctly, but my JavaScript implementation isn't yielding the same results. I'm working with Javascript in a Docker container on Ubuntu 22.04. I'm open to any suggestions.