Home > Mobile >  Get Full Date Only in Regex
Get Full Date Only in Regex

Time:01-18

I have strings that includes the dates. I wanted to get the full date only. If there's no year, just add the current year of 4 digits.

Sample

Nov 29 2019
abc 0 May 30 2020
ddd Apr 3 2021 efg
0 Jan 3 hellodewdde deded

https://regex101.com/r/pLUQNe/1

Regex

(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}?)

CodePudding user response:

You may use the following regex pattern:

(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}(?: \d{4})?

var dates = ["Nov 29 2019", "abc 0 May 30 2020", "ddd Apr 3 2021 efg", "0 Jan 3 hellodewdde deded", "Green eggs and ham"];
var months = "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
var regex = new RegExp(months   " \\d{1,2}(?: \\d{4})?");
var matches = [];

for (var i=0; i < dates.length;   i) {
    var date = dates[i].match(regex);
    if (date != null) {
        if (date[0].match(/ \d{4}$/)) {
            matches.push(date[0]);
        }
        else {
            matches.push(date[0]   " "   new Date().getFullYear());
        }
    }
}

console.log(matches);

The logic here is that we detect if the matching date has a ending 4 digit year. If not, then we append the current year to the month/day match.

  •  Tags:  
  • Related