CodexBloom - Programming Q&A Platform

Regex scenarios to Match Complex Date Formats in JavaScript - Handling Multiple Patterns

๐Ÿ‘€ Views: 62 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
regex javascript date-formatting JavaScript

I've tried everything I can think of but I'm maintaining legacy code that I need some guidance on I'm working on a project in JavaScript where I need to validate and extract dates from a variety of string formats... The question is that my regex isn't capturing all the variations I expect. Currently, I'm trying to match dates in formats like 'MM/DD/YYYY', 'DD-MM-YYYY', and 'YYYY.MM.DD'. Hereโ€™s the regex Iโ€™ve been using: ```javascript const regex = /(?:\d{1,2}[\/.-]\d{1,2}[\/.-]\d{2,4}|\d{4}[\.\-]\d{1,2}[\.\-]\d{1,2})/g; ``` However, when I test it against a string like 'The event is on 03-15-2023 or 2023.05.01', it correctly matches '03-15-2023' but fails to capture '2023.05.01'. I tried breaking down the regex into separate patterns to see if it was just one part that was failing, but even when I isolate the components, I still need to get it to match all intended formats. Additionally, I noticed that when I use the `test` method of the regex object, it only returns a match for the first valid format, ignoring others in the string. Hereโ€™s how Iโ€™m currently testing it: ```javascript const testString = 'The event is on 03-15-2023 or 2023.05.01'; const matches = testString.match(regex); console.log(matches); ``` This prints out `['03-15-2023']`, but I was expecting it to capture both dates. I'm wondering if there's a more effective way to structure my regex or if I'm missing something fundamental about capturing multiple patterns in one go. Any guidance on how to correct this would be greatly appreciated! This is for a desktop app running on Windows 11. Thanks for any help you can provide! Has anyone else encountered this? Any advice would be much appreciated.