Home >Web Front-end >JS Tutorial >How to Convert RGB to Hex Color Values in JavaScript?

How to Convert RGB to Hex Color Values in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 16:06:10977browse

How to Convert RGB to Hex Color Values in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn