1

This is a basic javascript question basically i was just going though this function below:

function hexToRgb(hex){
  // By Tim Down - http://stackoverflow.com/a/5624139/3493650
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
     return r + r + g + g + b + b;
  });
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
  } : null;
};

As you can see this code is already taken from another thread on SO, now my question is specifically about the peice of code:

var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
     return r + r + g + g + b + b;
  });

The parameters of the replace function I.E. m, r, g , b are basically the following as i see in my dev tools:

m = "#fff",
r = f
g = f
b = f

I see the aboe in my dev tools , the option i had passed is #fff.

Now my question is who is passing there parameters ? does the regex have anything to do with parameters being passed ? who is passing these parameters ? m,r,g,b ? I have checked what the regex is doing HERE , but i still don't understand who is passing the parameters to this function ?

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
  • `.replace` is passing the parameters, you can see the arguments it passes here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – elclanrs Apr 03 '16 at 13:57
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter – Matthew Herbst Apr 03 '16 at 14:00
  • 1
    The first argument is the entire match. Later args are each capture group. This function is the same as passing the _String_ `"$1$1$2$2$3$3"` – Paul S. Apr 03 '16 at 14:17

1 Answers1

2

That is an anonymous function defined which is passed as a parameter to the replace function which passes the parameters m,r,g,b as arguments to the anonymous function.

The line: hex.replace(shorthandRegex, function(m, r, g, b) { is calling the replace function on the hex variable passing in two parameters. The first is shorthandRegex and the second is the anonymous function. The anonymous function then gets the parameters from the replace function when it calls it.

An example of this pattern is:

var func = function(a, b) {
 console.log(a);
 b(1,2,3,4);
}

func(1, function(a,b,c,d) {
 console.log(a);
 console.log(b);
 console.log(c);
 console.log(d);
});

This should output 1, 1, 2, 3, 4 to the console.

This is also known as the callback pattern which is explained here: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19