skip to Main Content

I try to extract and reorganize a date string? 2024-11-21 into 21-11-2024

Any help would be… Helpful 🙂

Thanks

I have a string in html

<h2 class="tg-item-meta-data tg-element-4">2024-11-21</h2>

I want to display date as 21-11-2024

I tried this to extract number

var number = parseInt(jQuery('.tg-item-meta-data tg-element-4').text()); alert(number);

But fails

How do I extract and reorganize a date string?

2

Answers


  1. Chosen as BEST ANSWER

    I add jQuery( document.querySelector('.tg-item-meta-data.tg-element-4').replaceWith(result) ); to display the correct format in the html code but it's not realy working, tag and style are different. Is there another code to replace the previous date by 'result' in the same html line?


  2. You can try like this.

    var dateElement = document.querySelector('.tg-item-meta-data.tg-element-4');
    
    var dateString = dateElement.textContent;
    var dateParts = dateString .split('-');
    
    var result = `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
    
    dateElement.textContent = result;
    <h2 class="tg-item-meta-data tg-element-4">2024-11-21</h2>

    And this is code with jQuery

    $(document).ready(function() {
        var dateString = $('.tg-item-meta-data.tg-element-4').text(); 
    
        var dateParts = dateString.split('-');
        var result = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
    
        $('.tg-item-meta-data.tg-element-4').text(result);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search