I am trying to sort date-time strings using Regex in my javascript code but am running into a problem. If the HH portion of the string “MM/DD/YYYY HH:MM:SS” is one digit, my program sorts that with a missing digit and is therefor a way smaller number and does not sort properly.
My regex is this (the part in question is in bold):
/^(\d{ 1,2 })[/- ](\d{ 1,2 })[/- ](\d{ 4 })[\s](\d{ 1, 2})[\:](\d{ 2 })[\:](\d{ 2 })[\s]([ AP]M)?/g
Is there a way to add a zero to the front of the HH if the number is one digit? And without using any .replace() methods, because that wont work in the section of my sort function.
Thanks in advance!
You can’t modify the string without using
replace. You can “normalize” a date that matches your regex:For today’s date, this would return:
The date components are sorted from biggest to smallest, which means a simple
.sort()call would arrange the dates in the right order with no fuss.NOTE: I edited your regex a little, but it still matches the same stuff. The only difference is that now if there is no AM or PM, the space at the end is no longer required.