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.