How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
const hex = x.toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Returns an array [r, g, b]
. Works also with shorthand hex triplets such as "#03F"
.
const hexToRgb = hex =>
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
,(m, r, g, b) => '#' + r + r + g + g + b + b)
.substring(1).match(/.{2}/g)
.map(x => parseInt(x, 16))
console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]
padStart()
methodconst rgbToHex = (r, g, b) => '#' + [r, g, b]
.map(x => x.toString(16).padStart(2, '0')).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.