Hello there!
I’m using a custom script to format numbers in a CMS list with thousand separators. It works perfectly on the first page, but not on page two and thereafter. Any idea why?
The custom script is below.
Thankful for any ideas!
Jacob
<script>
document.addEventListener("DOMContentLoaded", function () {
// Define the separator function
function formatNumberWithSeparator(number, separator) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separator);
}
// Select all elements with the custom data attribute
const elements = document.querySelectorAll("[data-format-number]");
// Loop through the elements and format the numbers
elements.forEach((el) => {
const separator = el.getAttribute("data-separator") || " "; // Default to space
const rawNumber = el.textContent.trim();
// Parse and format the number
if (!isNaN(rawNumber) && rawNumber !== "") {
el.textContent = formatNumberWithSeparator(Number(rawNumber), separator);
}
});
});
</script>```