$<span id="money">0</span>
I have this span in my html document that is linked to my javascript.
function formatNumber(e){
var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
val = this.textContent.replace(/^0+|\.|,|\s/g,"")
res;
if (val.length) {
res = Array.prototype.reduce.call(val, (p,c) => c + p) // reverse the pure numbers string
.match(rex) // get groups in array
.reduce((p,c,i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
res += /\.|,/.test(res) ? "" : ".0"; // test if res has (.) or (,) in it
this.value = Array.prototype.reduce.call(res, (p,c) => c + p);// reverse the string and display
}
}
var mySpan = document.getElementById("money");
mySpan.addEventListener("DOMSubtreeModified", formatNumber);
The code above is the function. I have to try and format the span displaying "money" into a number separated by commas every time the span is updated, for example 1234 would become 1,234 and so on. However the code does not appear to be working as expected and the number remains unformatted.