Skip to content

Instantly share code, notes, and snippets.

@daneden
Created July 23, 2020 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daneden/97635fa8310703393cb45f1178497ca1 to your computer and use it in GitHub Desktop.
Save daneden/97635fa8310703393cb45f1178497ca1 to your computer and use it in GitHub Desktop.
// $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