Created
January 8, 2019 10:43
-
-
Save ali-master/70bd2ad70f516a0d5b7c06a0f63d3404 to your computer and use it in GitHub Desktop.
Convert Hex color code to RGB and vice versa.
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
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