Javascript hex to rgb script - what's this function?

From this site(https://www.html-code-generator.com/javascript/color-converter-script) I found this script:

function HEXtoRGB(hex) {
    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;
}

So far, I’ve figured out this:
/^#?([a-f\d])([a-f\d])([a-f\d])$/i is a regex that searches for # (optional) in the start of the string
([a-f\d]) searches for any letter between a-f and then a digit, then does it three times.
i makes it case-insensitive.

There’s also a ternary operator that returns an object with the hexadecimal parsed numbers.

Now what does the function in hex.replace do?

function (m, r, g, b) {
        return r + r + g + g + b + b;
}

I know that you can do str.replace(regex, "a") or something, but what does the function do? I don’t see any params entering it.

The replace function takes either a string or a function as its second parameter. If a function, the arguments passed will depend on the regex.

In this case, m is the matched string, and r, g and b are the results of the 1st, 2nd and 3rd capturing group respectively.

As an exemple:

If we have the string #ABC

m equals #ABC
r equals A
g equals B
b equals C

The return value would then be AABBCC

3 Likes

Yeah, I rewrote this function myself - it seems like .exec has the same function as .match with regexes.