I have this code (assume unable to modify)
<div >
<div >
<span >2026-01-31-08:00</span>
</div>
<div >
<span >2025-03-34-06:00</span>
</div>
<div >
<span >N/A</span>
</div>
<div >
<span >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?
CodePudding user response:
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 >
<div >
<span >2026-01-31-08:00</span>
</div>
<div >
<span >2025-03-34-06:00</span>
</div>
<div >
<span >N/A</span>
</div>
<div >
<span >N/A</span>
</div>
</div>
CodePudding user response:
You can use :contains('-') to search for the hyphen.
$(".content:contains('-')").each(function(){
let date = $(this).html().split("-");
date.pop();
$(this).html(date[1] "/" date[0]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
<span >2026-01-31-08:00</span>
</div>
<div >
<span >2025-03-34-06:00</span>
</div>
<div >
<span >N/A</span>
</div>
<div >
<span >N/A</span>
</div>
</div>