Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created January 8, 2019 10:43
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 ali-master/70bd2ad70f516a0d5b7c06a0f63d3404 to your computer and use it in GitHub Desktop.
Save ali-master/70bd2ad70f516a0d5b7c06a0f63d3404 to your computer and use it in GitHub Desktop.
Convert Hex color code to RGB and vice versa.
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i
hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b)
const 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
}
function rgbToHex(r, g, b) {
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment