Replace
The replace function accepts a regular expression, and replaces each match with a value. The replacement value is determined by the function you pass to replace
as the second argument.
Anonymous functions as callbacks
The anonymous function is not (visibly) called from the JavaScript code, but is called internally by the replace
function. You don't pass the function result but the function itself to replace
, so replace
can call your function to process the matches. This way you can 'inject' behaviour into JavaScript's built-in functions. This is a common concept in JavaScript, and you'll encounter this on many occasions.
The '.' wildcard in the pattern
So, the function is called for each match of the pattern. The core of this pattern is the dot .
character. It is a wildcard meaning 'any character'. So any character in the given number is matched by the dot. The effect of this, is that the function is called for each separate character in the number.
Arguments and inner workings of the callback
Then the arguments a
, c
and i
. The meaning of the arguments of the callback function are of course documented for the replace function, but it may become a bit clear at once if you output c, i and a to the console as I've done in the snippet below.
function numFormat(n) {
return n.toFixed(0).replace(/./g, function(c, i, a) {
console.log(a + ',' + i +',' + c);
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
alert(numFormat(107784));
The parameters of the function are the matched substring (c
), which is one character each time (as matched by the pattern), the offset/string position (i
) of the match, and the whole string (a
).
Using the offset i
, a calculation is made to see if it is the third character or not. If so, the character c
is returned with a comma in front of it, otherwise, just the character is returned. i > 0
is added as an extra condition to prevent a comma at the start of the string. c !== "."
seems to be obsolete and may be a leftover from an attempt to support floating point numbers as well.
All these returned strings are put back together (again, internally by replace
) and will form the return value of the replace function.
Additional documentation