Created
August 29, 2021 15:55
-
-
Save iconifyit/340475f50560c59510606d9b713c9a1a to your computer and use it in GitHub Desktop.
RGB-to-Hexadecimal and Hexadecimal-RGB conversion
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
const hexToRgb = (hex) => { | |
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; | |
} | |
module.exports.hexToRgb = hexToRgb; | |
const rgbToHex = (r, b, g) => { | |
const toHex = (c) => { | |
let hex = c.toString(16); | |
return hex.length == 1 ? "0" + hex : hex; | |
} | |
return toHex(r) + toHex(g) + toHex(b); | |
} | |
module.exports.rgbToHex = rgbToHex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment