Home > Mobile >  Add Year If Missing in Regex and Javascript
Add Year If Missing in Regex and Javascript

Time:01-18

I'm getting the full date from the date field. I wanted to if the fulldate string is found, use it otherwise use its the the month with words, in this case Nov 29. In my code below, 2019 is already there, so it must be used.

Expected Output should be like FOR EXAMPLE

2019-11-29T12:00:00.000Z

let date = "0 Hi Nov 29 HELLO - 29112019";
let months = "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
let regex = new RegExp(months   " \\d{1,2}(?: \\d{4})?");

const result = date.match(regex).match(/ \d{4}$/)
                  ? date.match(regex).match(/ \d{4}$/)
                  : moment(
                      date.match(regex)  
                        " "  
                        new Date().getFullYear()
                    ).toDate() || "";
                    
                    
 console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

You need to pass the date in the recognizable format.

Here is one possible solution:

let date = "0 Hi Nov 29 HELLO - 21112019";
let months = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
let regex = new RegExp("(?:.*\\D)?((?:0?[1-9]|[12]\\d|3[01])(?:0?[1-9]|1[0-2])(?:19|20)\\d{2})|"   months   "\\s (\\d{1,2})(?:\\s (\\d{4}))?");

let match = date.match(regex);
if (match) {
  if (match[1]) {
    console.log(moment(match[1], "DDMMYYYY").format("YYYY-MM-DD[T]HH:mm:ss[Z]"));
  } else {
    if (match[4] === undefined) {
      match[4] = new Date().getFullYear()
    }
    console.log(moment(`${match[2]} ${match[3]} ${match[4]}`, "MMM DD YYYY").format("YYYY-MM-DD[T]HH:mm:ss[Z]"));
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Note that the pattern will look like (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s (\d{1,2})(?:\s (\d{4}))?, and will match the month name into Group 1, the day into Group 2 and year - if present - in Group 3. The \s matches one or more whitespaces. If Group 3 does not match, match[2] will be undefined, and you can replace it with the current year.

The MMM means Month name in locale set by moment.locale().

Mind that the pattern you are using has no bonundaries on both sides and can match being a part of a longer substring. Thus, it makes sense to make it more precise with at least word boundaries:

let regex = new RegExp("\\b"   months   "\\s (\\d{1,2})(?:\\s (\\d{4}))?\\b");

Or, with a word boundary at the start and a (?!\d) lookahead at the end (to make sure there are no other digits after day/year):

let regex = new RegExp("\\b"   months   "\\s (\\d{1,2})(?:\\s (\\d{4}))?(?!\\d)");
  •  Tags:  
  • Related