Converting RGB to Hex Color Values in JavaScript
The jQuery function $('#selector').css('backgroundColor') provides the RGB value of an element's background color. If you need to obtain the hex value instead, here's a comprehensive solution:
One-Line Function (Updated 2021):
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('')}`
This function supports both RGB and RGBA values.
Cross-Browser One-Liner (ES5 ):
const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`
This alternative function works only for RGB values.
Example Usage:
console.log(rgb2hex('rgb(255, 255, 255)')); // '#ffffff' console.log(rgb2hex('rgb(0, 0, 0)')); // '#000000'
The above is the detailed content of How to Convert RGB to Hex Color Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!