I have two dateString formats like :date-f1:+2 and :date-f2:-1, if the incoming string is in date-f1:+2 format, I need to console.log as processedDate.format("YYYY-MM-DD"), but if the incoming string is in :date-f2:-1 format, I need to console.log as processedDate.format("DD/MM/YYYY"). I have tried the below, but getting an exception Cannot read properties of null (reading '1')", could someone please advise;
let dateString = ":date-f1:+2"; // or ":date-f2:-1"
function datesParse(dateString) {
let matchFormat = dateString.match(/^:date-f1:(|):date-f2:(?:([\-\+])([0-9]+)+)?$/);
let processedDate = moment();
if (matchFormat[1] === "-") {
processedDate = processedDate.subtract(matchFormat[2], 'days');
console.log("Date::"+processedDate.format("DD/MM/YYYY"));
} else if (matchFormat[1] === "+") {
processedDate = processedDate.add(matchFormat[2], 'days');
console.log("Date::"+processedDate.format("DD/MM/YYYY"));
} else if (matchFormat[1] === "-") {
processedDate = processedDate.subtract(matchFormat[2], 'days');
console.log("Date::"+processedDate.format("YYYY-MM-DD"));
} else if (matchFormat[1] === "+") {
processedDate = processedDate.add(matchFormat[2], 'days');
console.log("Date::"+processedDate.format("YYYY-MM-DD"));
}
}
datesParse(dateString);
(:date-f1:|:date-f2:)?:date-f1:+2and:date-f2:-1) where literally nothing changes, then instead of regex useif elseelse for checking. Using regex here seems wasteful.includeslike below, then we need to check-f1and+or-operator at the same time ..right ?let word = "-f1" let operator = "+" if (dateString.includes(word) && dateString.includes(operator)) { ....