soccerway
soccerway

Reputation: 11961

Using regex how to perform string match to get a different date format

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);

Upvotes: 0

Views: 62

Answers (1)

anotherGatsby
anotherGatsby

Reputation: 1598

I modified your regex and also added named capture groups, try this: /^:date-(?<word>f[12]):(?:(?<operator>[-+])(?<number>[0-9]+)+)?$/gm

Test here: https://regex101.com/r/cNNHA5/1

With capture groups you can access each of those captured elements easily:

let line = ':date-f1:+2';

let pattern = /^:date-(?<word>f[12]):(?:(?<operator>[-+])(?<number>[0-9]+)+)?$/gm

let match = pattern.exec(line)

console.log('word', match.groups.word)
console.log('operator', match.groups.operator)
console.log('number', match.groups.number)

and use them for checking like:

if (dateString.includes(match.groups.word) && dateString.includes(match.groups.operator))

so you dont have to create extra vars word and operator.

Upvotes: 1

Related Questions