I have this date parsed from an api as a string:
DD-MM-YYYY but sometimes the date is DD-M-YYYY or even D-M-YYYY.
For example:
4-1-2013
or
10-10-2013
or 7-4-2013
The year is always 4 digits but days or months sometimes get one digit. How can I manually (with JS) add 0 in front of a every single digit ?
I am using moment.js for some calculations thus I am remove the ‘-‘ using
date.replace("-", "")
to get a whole number (eg. 4-1-2013 = 412013) so I can use it with moment.js but if its a single digit, it all gets messed up.
You can normalise your strings first like this:
which will take any “word” that is just a single digit and prepend a zero.
Note that to globally replace every
-you must use the regexp version of.replace– the string version you’ve used only replaces the first occurrence, therefore:will do everything you require.