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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With