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

How Can I Convert RGB Color Values to Hex in JavaScript?

Patricia Arquette
Release: 2024-12-19 10:22:13
Original
913 people have browsed it

How Can I Convert RGB Color Values to Hex in JavaScript?

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('')}`
Copy after login

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('')}`
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template