Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// $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