Open In App

How to extract date from a string in dd-mmm-yyyy format in JavaScript ?

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to extract date from a given string of format “dd-mmm-yyyy” in JavaScript. We have a string, and we want to extract the date format “dd-mmm-yyyy” from the string.

Example:

// String
str = "India got freedom on 15-Aug-1947"

// Extracted date from given string in
// "dd-mmm-yyyy" format
date = 15-Aug-1947

Approach:

  • There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. 
  • The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using the match() method.

Syntax:

str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi);

Example: This example shows the use of the above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>

<body>
    <!-- div element with inline styles -->
    <div style="color: red; background-color: black; margin: 40px 40px; padding: 20px 100px;">
        India got freedom on 15-Aug-1947.
        <p></p>
        <button>
            Click the button to see date
        </button>
    </div>

    <!-- Link to JQuery CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>

</html>
JavaScript
// After clicking the button it will 
// show the height of the div
$("button").click(function () {

    // String that contains date
    var str = "India got freedom on 15-Aug-1947"

    // Find "dd-mmm-yyyy" format in the string
    var result =
        str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi);

    // Show date on screen in 
    // format "dd-mmm-yyyy"
    $("p").html(result);
});

Output:

extract date from a string in dd-mmm-yyyy format



Next Article

Similar Reads