CodexBloom - Programming Q&A Platform

Regex Not Capturing Date Formats Correctly in JavaScript - implementing Different Delimiters

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

I've encountered a strange issue with I've been working on this all day and After trying multiple solutions online, I still can't figure this out. I'm working on a personal project and This might be a silly question, but I'm trying to extract dates from a string using regex in JavaScript, but I'm running into issues with different date formats and delimiters. My goal is to match dates in the formats `MM-DD-YYYY`, `DD/MM/YYYY`, and `YYYY.MM.DD`. However, my regex seems to either capture the wrong groups or fails to match entirely when the delimiters vary. Here's the regex I've written: ```javascript const regex = /(?:(\d{2})[\/\.\-](\d{2})[\/\.\-](\d{4}))|(?:(\d{4})[\/\.\-](\d{2})[\/\.\-](\d{2}))/g; ``` I've tried using capturing groups for the different formats, but I keep getting unexpected results when I test it against strings like `12-25-2023`, `25/12/2023`, and `2023.12.25`. The regex only captures the first date correctly and fails for the others. I also attempted to test it with the `String.match()` method, like this: ```javascript const testString = 'Important dates: 12-25-2023, 25/12/2023, and 2023.12.25'; const matches = testString.match(regex); console.log(matches); ``` The output is inconsistent; sometimes it returns only the first date, and other times it doesn't return any matches at all. I'm concerned that the delimiters might be the scenario, but I need to pinpoint what's going wrong. Can anyone suggest how to adjust my regex so that it captures all the required date formats correctly? Any insights or examples would be greatly appreciated! What am I doing wrong? My development environment is Windows. What's the best practice here? I'd love to hear your thoughts on this. My team is using Javascript for this desktop app.