skip to Main Content

I have this code (assume unable to modify)

<div class="parent">
    <div class="wrap">
        <span class="content">2026-01-31-08:00</span>
    </div>
    <div class="wrap">
        <span class="content">2025-03-34-06:00</span>
    </div>
    <div class="wrap">
        <span class="content">N/A</span>
    </div>
    <div class="wrap">
        <span class="content">N/A</span>
    </div>
</div>

The "2026-01-31-08:00" are supposed to be dates, "N/A" should stay the same. I’m trying to format the dates by cutting off the extras with .slice, and format it to say "01/2026" and "03/2025" while the "N/A" stay the same.

I tried to use :contains to select the ones with number then format it but with no luck. Any ideas how to do so?

2

Answers


  1. You’ll want to filter the elements by matching their content to a regular expression. Then replace the contents of those elements with the new text

    const dateMatcher = /(d{4})-(d{2})-d{2}-d{2}:d{2}/;
    
    $(".content")
      .filter((_, { textContent }) => dateMatcher.test(textContent))
      .text((_, date) => {
        const [, year, month] = date.match(dateMatcher);
        return `${month}/${year}`;
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
    <div class="parent">
        <div class="wrap">
            <span class="content">2026-01-31-08:00</span>
        </div>
        <div class="wrap">
            <span class="content">2025-03-34-06:00</span>
        </div>
        <div class="wrap">
            <span class="content">N/A</span>
        </div>
        <div class="wrap">
            <span class="content">N/A</span>
        </div>
    </div>

    It’s 2022 and you might not need jQuery

    const dateMatcher = /(d{4})-(d{2})-d{2}-d{2}:d{2}/;
    
    Array.from(document.querySelectorAll(".content"))
      .filter(({ textContent }) => dateMatcher.test(textContent))
      .forEach((el) => {
        const [, year, month] = el.textContent.match(dateMatcher);
        el.textContent = `${month}/${year}`;
      });
    
    Login or Signup to reply.
  2. You can use :contains(‘-‘) to search for the hyphen.

    $(".content:contains('-')").each(function(){
      let date = $(this).html().split("-");
      
      $(this).html(date[1] + "/" + date[0]);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="parent">
        <div class="wrap">
            <span class="content">2026-01-31-08:00</span>
        </div>
        <div class="wrap">
            <span class="content">2025-03-34-06:00</span>
        </div>
        <div class="wrap">
            <span class="content">N/A</span>
        </div>
        <div class="wrap">
            <span class="content">N/A</span>
        </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search