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

How to Convert RGB to Hex Color Codes in JavaScript?

Barbara Streisand
Release: 2024-12-10 14:21:11
Original
320 people have browsed it

How to Convert RGB to Hex Color Codes in JavaScript?

Extracting Hex Color Codes from RGB Values

Obtaining RGB values of elements' backgrounds using jQuery may not always suffice. You may need to convert these values to their hexadecimal counterparts. This code snippet demonstrates how to extract RGB values:

$('#selector').css('backgroundColor');
Copy after login

Our goal is to obtain the corresponding hex values for the RGB values.

Solution

The TL;DR solution provides a concise one-line function that handles both RGB and RGBA formats:

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

Updated Solution (2021)

Modern browsers now support ECMAScript 5 and 2015 features, allowing for a more elegant solution:

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

This updated function simplifies the transformation from RGB to hex color codes.

The above is the detailed content of How to Convert RGB to Hex Color Codes 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