You can also use this regex /^\d\.|(?<=\.)\d\./g
it will select the first number and the number after the first dot, so it will only select date and month on your format.
You can use this like the code bellow
let regex = /^\d\.|(?<=\.)\d\./g;
console.log("8.8.2014".replace(regex,
str => `0${str}`));
console.log("25.06.2014".replace(regex,
str => `0${str}`));
console.log("9.06.2014".replace(regex,
str => `0${str}`));
console.log("08.7.2014".replace(regex,
str => `0${str}`));
console.log("1.1.1998".replace(regex,
str => `0${str}`));
Now I'm gonna explain it part by part
regex
The regex is broken by a |
which tells it to either match expression before it or after it.
The first part is ^\d\.
, if you know the basics of regex, you'll know that it means see if there is a number right after which there is a dot at the beginning, it selects the date if there is only one digit representing it.
The second part is (?<=\.)\d\.
, this part first sees if there is a dot before the string that is to be selected, then it sees if there is only one number after it then a dot. It will select the month if there is only one digit representing it.
Here the first part (?<=.) tells java script to seek for dot but not select it, if there is no dot before the number it won't select the string.
Now the last part g makes it select every instance of string which is matched.
So for the first example it selects the strings "8." and "8."
.replace
.replace
is a string function taking two argument, first the string/regex to match, in my code it is a regex.
Second is a string or a callback that returns a string, in my code it's a callback.
The callback can get the an argument which is the matched string.
Then I add the "0" before the matched string with a template string.
So the ending output is
08.08.2014
25.06.2014
09.06.2014
08.07.2014
01.01.1998
Hope my explanation helped.
I might be wrong at some places, as I'm still learning and use regex or even the callback of replace not very often.
Hope there weren't many mistakes.
If I'm wrong somewhere please let me know.