CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Custom Date Formats in JavaScript - Handling Multiple Delimiters

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
regex javascript date JavaScript

I've been banging my head against this for hours. I'm converting an old project and I'm struggling with a regex pattern in JavaScript that needs to extract dates formatted in various ways from a string. The dates can be formatted like `MM/DD/YYYY`, `DD-MM-YYYY`, or even `YYYY.MM.DD`. However, there can be inconsistent delimiters like slashes, dashes, or periods, sometimes even mixed together. For example, my input string could be something like: `The event is on 12/25-2023 and 2023.01.15.` I've tried using the following regex pattern, but it doesn't seem to account for all the edge cases: ```javascript const regex = /\b(\d{1,2}[/-\.]{1}\d{1,2}[/-\.]{1}\d{4})\b/g; const input = 'The event is on 12/25-2023 and 2023.01.15.'; const matches = input.match(regex); console.log(matches); ``` While this correctly captures `12/25-2023`, it fails to match `2023.01.15`. I also noticed that it doesn't handle the case where the month might be represented with a single digit (e.g., `1/5/2023`). I would like my regex to handle these variations more robustly, ideally capturing all valid date formats regardless of delimiters. Can someone provide insights into how to improve my regex pattern to account for these variations? I'm using Node.js version 14 and would appreciate any recommendations on best practices as well. I'm working on a application that needs to handle this. What's the best practice here? This is part of a larger mobile app I'm building. Is this even possible? I've been using Javascript for about a year now. Any pointers in the right direction?