CodexBloom - Programming Q&A Platform

Regex for Extracting Date Ranges in JavaScript - Trouble with Overlapping Dates

πŸ‘€ Views: 62 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-22
regex javascript date JavaScript

I'm confused about I've spent hours debugging this and I'm trying to use regex to extract date ranges from a string that contains multiple date entries in the format `YYYY-MM-DD to YYYY-MM-DD`... The scenario arises when the date ranges overlap or are not properly formatted. For example, the string I'm working with is: `2023-01-01 to 2023-01-05, 2023-01-04 to 2023-01-10, and 2023-01-15 to 2023-01-20.` I want to correctly capture all unique date ranges without duplicating any overlapping ranges. I've tried the following regex pattern: ```javascript const regex = /\d{4}-\d{2}-\d{2} to \d{4}-\d{2}-\d{2}/g; const dateRanges = inputString.match(regex); ``` However, this only captures the date ranges but doesn't guide to consolidate overlapping ones. I ended up with an array like `['2023-01-01 to 2023-01-05', '2023-01-04 to 2023-01-10', '2023-01-15 to 2023-01-20']`, which doesn’t eliminate the overlap between the first two ranges. I thought about parsing the date strings into actual Date objects and then checking for overlaps programmatically, but I'm unsure how to implement this effectively. Any suggestions on how to identify and consolidate overlapping date ranges either directly within the regex or through a subsequent processing step would be greatly appreciated! Also, I'm using Node.js v14. Thanks in advance for your help! This is happening in both development and production on Linux. Could someone point me to the right documentation? This is my first time working with Javascript 3.10. Could this be a known issue?