JavaScript/Digit grouping

Digits can be grouped in JavaScript by inserting separation characters after as many digits as the length of a digit group. Typically, the separation character is a comma, and there are three digits per group. The process of inserting separation characters is repeated as many times as the number's length divided by the length of a digit group, and that count is floored (rounded down).

The script also verifies whether the input is valid, and avoids placing a trailing separation character after the number.

The code below is commented to help you understand the purposes of individual lines.