Search code examples
javascripthtmljquery

How to parse date from data after page loading


After page loading, the html rendered is like that

<h3>Lorem ipsum dolor sit</h3>
<p>Meeting scheduled for 7/19/26, You should receive the email confirmation shortly.</p>
<h4>Lorem ipsum dolor sit</h4>
<p>lorem ipsum dolor sit</p>

Now I want to change the date format like this July 19th via jQuery or JavaScript so that para should be like that

Meeting scheduled for July 19th, You should receive the email confirmation shortly.

Solution

  • Can you try this ?

    The output is written on the console as well as the body itself, you can amend the script to suit your needs.

      function getOrdinal(n) {
            let ord        = ["st", "nd", "rd"]
            let exceptions = [11, 12, 13]
            let nth        = ord[(n % 10) - 1] == undefined || exceptions.includes(n % 100) ? "th" : ord[(n % 10) - 1]
            return n + nth
        };
    
        var temp    = document.getElementsByTagName("p")[0].innerHTML 
        temp        = temp.replace(',','');
    
        var strDate = temp.match(/\d{1,2}\D\d{1,2}\D(\d{4}|\d{2})/g)
        var objDate = new Date(strDate);
    
        var myDate  = objDate.getDate();
        var myMonth = objDate.toLocaleString('default', { month: 'long' });
        var myYear  = objDate.getFullYear();
        
        var myStr   = temp.replace(strDate, myMonth + ' ' + getOrdinal(myDate) + ', ' + myYear + '.');
    
        console.log(myStr);
        document.getElementsByTagName("p")[0].innerHTML= myStr;
    <h3>Lorem ipsum dolor sit</h3>
        <p>Meeting scheduled for 7/19/26, You should receive the email confirmation shortly.</p>
        <h4>Lorem ipsum dolor sit</h4>
    <p>lorem ipsum dolor sit</p>