By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Match the Dates - JavaScript task

+2 votes

Write a JS function that finds and extracts all the dates in the given sentences. The dates should be in format
d-MMM-yyyy. Example: 12-Jun-1999, 3-Dec-2017.

The input comes as an array of strings. Each string represents a sentence.


I am born on 30-Dec-1994.
This is not date: 512-Jan-1996.
My father is born on the 29-Jul-1955.

30-Dec-1994 (Day: 30, Month: Dec, Year: 1994)
29-Jul-1955 (Day: 29, Month: Jul, Year: 1955)

1-Jan-1999 is a valid date.
So is 01-July-2000.
I am an awful liar, by the way – Ivo, 28-Sep-2016.

1-Jan-1999 (Day: 1, Month: Jan, Year: 1999)
28-Sep-2016 (Day: 28, Month: Sep, Year: 2016)

The output should be printed on the console. The output should consist of all extracted VALID dates. Each element should be printed on a new line.

asked in JavaScript category by user samfred5830

1 Answer

+1 vote

Here is the JS code:

function matchDates(arrStr) {
    let pattern = /\b([0-9]{1,2})-([A-Z][a-z]{2})-([0-9]{4})\b/g;
    let dates = [], match;

    for (let arrS of arrStr) {
        while (match = pattern.exec(arrS)) {
            dates.push(`${match[0]} (Day: ${match[1]}, Month: ${match[2]}, Year: ${match[3]})`);

        "I am born on 30-Dec-1994.",
        "This is not date: 512-Jan-1996.",
        "My father is born on the 29-Jul-1955."


answered by user eiorgert
function md(input) {

    let pattern = /\b([0-9]{1,2})-([A-Z][a-z]{2})-([0-9]{4})\b/g;

    let dates = [], match;

    for (let currentSentence of input) {
        let match = pattern.exec(currentSentence);

        while (match) {
            dates.push(match[0] + ` (Day: ${match[1]}, Month: ${match[2]}, Year: ${match[3]})`);
            match = pattern.exec(currentSentence)