Created
July 23, 2020 16:57
-
-
Save daneden/97635fa8310703393cb45f1178497ca1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $0 is web inspector's reference to the current element | |
$0.style.backgroundColor | |
// run a regex to get the values for r, g, b, and optionally a | |
.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})(, ?([0-9.]{1,3}))?\)/) | |
// filter out the regex results we don't care about | |
.filter((e, i) => { | |
switch (i) { | |
case 1: // red | |
case 2: // green | |
case 3: // blue | |
case 5: // alpha (group 4 is the optional capture group surrounding it) | |
return true | |
break | |
default: // ignore everything else | |
return false | |
} | |
}) | |
// Now we reduce the array of values to a HEX string | |
.reduce( | |
(acc, curr) => | |
// if alpha is undefined we want to just return the hex code | |
// also, whole-number values need to be padded for a full HEX code | |
curr !== undefined ? acc + Number(curr).toString(16).padEnd(2, "0") : acc, | |
"#" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment