0
$<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.

aknosis
  • 3,602
  • 20
  • 33
  • Why don't you just use [Number.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) instead of that.... complicated mess? –  Sep 20 '17 at 17:07
  • I tried that originally but encountered the same problem of it not updating – FatboyJames Sep 20 '17 at 17:25
  • Yes, because `span` elements don't have a `value` attribute. –  Sep 20 '17 at 17:28
  • Is there a way to get around that? – FatboyJames Sep 20 '17 at 17:30
  • Possible duplicate of [How do I change the text of a span element in JavaScript](https://stackoverflow.com/questions/1358810/how-do-i-change-the-text-of-a-span-element-in-javascript) –  Sep 20 '17 at 17:30
  • No, there's no way around that. You can, though, set the text using the same attribute you used to retrieve the text.... –  Sep 20 '17 at 17:31
  • I still don't seem to be having any luck getting this to work – FatboyJames Sep 20 '17 at 17:42

1 Answers1

0

See this jsfiddle. The funcation at work being

function format(){
  var dollars = document.getElementsByClassName('money');
  for(var i = 0; i < dollars.length; i++){
      dollars[i].innerHTML = dollars[i].innerHTML.replace(/(\d{1,3})(?=\d{3})/g, '$1,');
  }
}

What I'm doing is pulling all elements with the class name "money", then reassigning their innerhtml to a regexed version of itself. The regex being

/(\d{1,3})(?=\d{3})/g
    (/d{1,3}) //Find a group of digits between 1 and 3 digits in length. assigned to $1
    (?= //Look ahead
       \d{3} //Look for exactly 3 digits
    )
/g //repeat until no more matches are found

Then, just insert a comma after $1 Note that this does not work for decimals greater than 3 digits, but money should never reach thousandths anyways.

Geoffrey H.
  • 160
  • 2
  • 17