3

I simply can't understand why the second and the third lines of output differs one from another:

alphabet_ASCII = '';
for (i=65; i<=90; i++) {
  alphabet_ASCII += i;
}
alphabet_ASCII += '<br>';

document.body.innerHTML += alphabet_ASCII;



document.body.innerHTML += 
  alphabet_ASCII.replace(/\d{2}/g, x=>String.fromCharCode(x));

document.body.innerHTML += 
  alphabet_ASCII.replace(/\d{2}/g, String.fromCharCode);

What's the difference between x=>String.fromCharCode(x) and String.fromCharCode?

1 Answers1

6

Because String.fromCharCode accepts multiple arguments, and replace calls the callback with more than just the one argument you're expecting: It calls the callback with:

  • All matching text
  • The contents of any capture groups (if any)
  • The index (offset) at which this match occurred
  • The whole string being acted on

More on MDN.

So in your second example, String.fromCharCode gets more arguments than in your first, and does its best with them. On the first callback, String.fromCharCode gets "65", 0, "6566676869707172737475767778798081828384858687888990" and so returns "A\u0000\u0000" (because the second argument is 0 and the third is invalid). On the second pass it gets "66", 2, "6566676869707172737475767778798081828384858687888990" and returns "B\u0002\u0000", etc.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I didn't know about the third and fourth args.. Nice to know, I will accept when possible –  Feb 11 '16 at 13:44
  • 1
    @WashingtonGuedes: Truthfully, neither did I, but when I saw the question I thought "I bet it's for the same reason you can't do that with `forEach`..." and looked it up. :-) – T.J. Crowder Feb 11 '16 at 13:45
  • 1
    Just to point you from where my question was [originated](http://codegolf.stackexchange.com/q/71735/48943) –  Feb 11 '16 at 17:37