JS Date: Add 0 in front of every single day or month
date, javascript, momentjs
Solution
You can normalise your strings first like this:
date = date.replace(/\b(\d{1})\b/g, '0$1');
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:
date = date.replace(/\b(\d{1})\b/g, '0$1').replace(/-/g, '');
will do everything you require.
Problem
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.