var string = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS'
I would like to get a date from the above string, remove all the other content and return like the below:
['2018-01-01', '2018-12-31', '201801', '201812']
Basically, YYYY-MM-DD, YYYY-MM-DD, YYYMM, YYYYMM.
I have tried the following but couldn’t progress more:
var res = string.match(/\d{2}([\/.-])\d{2}\1\d{4}/g);
=> ['01/01/2018', '31/12/2018']
Then another function is to get the YYYYMM part.
var arr = res[0].split("-");
return arr[0]+arr[1];
=> '201801'
Is it possible to get the four elements in a single array in an efficient way?
Thanks in advance!
>Solution :
I would do it in two steps. Find the dates, then format them.
const formatDateParts = (string) => {
const [day, month, year] = string.split('/');
return [[year, month, day].join('-'), `${year}${day}`];
};
const [_, date1, date2] = string.match(/(\d{2}\/\d{2}\/\d{4})-(\d{2}\/\d{2}\/\d{4})/);
const [date1Format, date1Condensed] = formatDateParts(date1);
const [date2Format, date2Condensed] = formatDateParts(date2);
const result = [date1Format, date2Format, date1Condensed, date2Condensed];