Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass the function directly into replace method?

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 Answers

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.

like image 66
T.J. Crowder Avatar answered Apr 23 '26 00:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!