Getting Hex Color Values from RGB
The jQuery provided allows you to retrieve the RGB value of an element's background color. However, what if you need the hex value instead?
Solution
To convert RGB values to hex values, consider the following one-line function:
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('')}`
Improved Answer (2021)
With advancements in EcmaScript features, a more concise and updated version of rgb2hex is:
const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`
Example Usage
You can utilize these functions as follows:
console.log(rgb2hex('rgb(0,0,0)')) // '#000000' console.log(rgb2hex('rgb(255, 255, 255)')) // '#ffffff' console.log(rgb2hex('rgb(255,0,0)')) // '#ff0000' console.log(rgb2hex('rgb(38, 170, 90)')) // '#26aa5a'
The above is the detailed content of How Can I Convert RGB Color Values to Hex in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!