Parsing Dates
Explore how we can parse dates and create Date objects by using regular expressions.
We'll cover the following
Problem statement
For the third exercise, let’s try to do something more practical. As the title suggests, you can easily use regular expressions to parse dates, which means you can grab a string that represents a date and turn it into the correct Date
object.
Of course, there are a variety of libraries published out there that actually deal with this in all the right ways, but, because we’re trying to understand the power of RegExps, we’ll just ignore that fact for the time being.
The exercise will consist of creating a function that can successfully turn any of the following strings into a correctly set Date
object:
- 2019-10-24
- Dec 23rd, 2019
We could get crazy and try to go for many other formats, but, for the sake of understanding the basics, this will do. Remember, your code needs to parse those strings and create a valid Date
object, which means that you need to capture specific parts of the string and parse them accordingly.
If you think about it, the logic for this function is simple. Just capture the three different parts of the date (year, month, and date) and return the new object using those captured values. The key, though, is to create the correct set of regular expressions.
Solution
Here is the full code for the script:
Get hands-on with 1200+ tech skills courses.