Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Created August 29, 2021 15:55
Show Gist options
  • Save iconifyit/340475f50560c59510606d9b713c9a1a to your computer and use it in GitHub Desktop.
Save iconifyit/340475f50560c59510606d9b713c9a1a to your computer and use it in GitHub Desktop.
RGB-to-Hexadecimal and Hexadecimal-RGB conversion
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