How to get hex color value rather than RGB value? How to get hex color value rather than RGB value? javascript javascript

How to get hex color value rather than RGB value?


TLDR

Use this clean one-line function with both rgb and rgba support:

const rgba2hex = (rgba) => `#${rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)$/).slice(1).map((n, i) => (i === 3 ? Math.round(parseFloat(n) * 255) : parseFloat(n)).toString(16).padStart(2, '0').replace('NaN', '')).join('')}`

2021 updated answer

Much time has passed since I originally answered this question. Then cool ECMAScript 5 and 2015+ features become largely available on browsers, like arrow functions, Array.map, String.padStart and template strings. So now it's possible to write an one-liner rgb2hex:

const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`// Use as you wish...console.log(rgb2hex('rgb(0,0,0)'))console.log(rgb2hex('rgb(255, 255, 255)'))console.log(rgb2hex('rgb(255,0,0)'))console.log(rgb2hex('rgb(38, 170, 90)'))