Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

Converting the other way:

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) {
  return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":

function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";

Answer from Tim Down on Stack Overflow
Top answer
1 of 16
1720

Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

Converting the other way:

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) {
  return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":

function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";

2 of 16
202

An alternative version of hexToRgb:

function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

Edit: 3/28/2017 Here is another approach that seems to be even faster

function hexToRgbNew(hex) {
  var arrBuff = new ArrayBuffer(4);
  var vw = new DataView(arrBuff);
  vw.setUint32(0,parseInt(hex, 16),false);
  var arrByte = new Uint8Array(arrBuff);

  return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}

Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.

🌐
LearnersBucket
learnersbucket.com › home › examples › interview › convert hex color to rgb in javascript
Convert HEX color to RGB in JavaScript - LearnersBucket
April 29, 2022 - //create full hex const fullHex ... parseInt(b+b, 16); // return {r, g, b} return { r, g, b }; } //convert hex to rgb const hex2rgb = (hex) => { if(hex.length === 4){ return fullHex(hex); } const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const ...
Discussions

[Share] RGB color parser in JavaScript
Awesome! This will be very handy in one of my projects :) Edit: damn. I mistook this for hsl to hex conversion. Any chance you can look into that too? The math behind it is way above my head :-( More on reddit.com
🌐 r/tasker
10
14
February 15, 2018
color2color.js - Simple JS to convert hex/RGB/RGBA/HSL/HSLA/HSV to hex/RGB/RGBA/HSL/HSLA/HSV string
Add LAB color space. I use it to compute perceptually equivalent color differences (e.g., to de-emphasize colors in a UI). More on reddit.com
🌐 r/programming
11
30
April 2, 2012
How come JavaScript converts HEX colors to RGB?
I believe it's in the css spec: [ https://drafts.csswg.org/css-color/#resolving-color-values] The computed and used value is the corresponding sRGB color, paired with the specified alpha channel and defaulting to opaque if unspecified). For example, the computed value of hsl(38.824 100% 50%) is rgb(255, 165, 0) More on reddit.com
🌐 r/webdev
7
11
June 14, 2022
How can I convert RGB or Hex into Hue?
Cached version available at http://web.archive.org/web/20161023150649/http://www.developers.meethue.com:80/documentation/hue-xy-values If you understand PHP, there's an sdk on github that has a convert function in it - https://github.com/sqmk/Phue/blob/master/library/Phue/Helper/ColorConversion.php More on reddit.com
🌐 r/Hue
7
2
November 7, 2017
🌐
Converting Colors
convertingcolors.com › blog › article › convert_hex_to_rgb_with_javascript.html
Converting Colors - Convert HEX to RGB with Javascript
String.prototype.convertToRGB = function(){ var aRgbHex = this.match(/.{1,2}/g); var aRgb = [ parseInt(aRgbHex[0], 16), parseInt(aRgbHex[1], 16), parseInt(aRgbHex[2], 16) ]; return aRgb; } console.log('1502BE'.convertToRGB()); //[21, 2, 190] Additionally, we should add a check that the string ...
🌐
JavaScripter
javascripter.net › faq › hextorgb.htm
Hex-to-RGB Color Converter
Hex-to-RGB Conversion JavaScript FAQ | JavaScript Colors FAQ · Question: How do I convert a hex color string (e.g. "FFFFCC") to numeric RGB values
🌐
HTML Code Generator
html-code-generator.com › javascript › color-converter-script
JavaScript Color Converter Script | HEX to RGB | HSL
<h1 id="preview-color"></h1> <input type="text" id="hex-color" value="#076591"> <button id="convert-hex-to-rgb">Convert</button> <script> // support hex format (#f00, #ff0000, f00, ff0000) document.getElementById("convert-hex-to-rgb").onclick = function(){ let hex_color = document.getElementById("hex-color").value; var preview_color = document.getElementById("preview-color"); let result = HEXtoRGB(hex_color ); if(!result){ preview_color.innerHTML= 'invalid color'; preview_color.style.backgroundColor = ''; preview_color.style.color = 'red'; return; } /* var red = result[0]; var green = result[1]; var blue = result[2]; let rgb = 'rgb('+red+','+green+','+blue+')'; */ // shorthand result let rgb = 'rgb('+result.join(', ')+')'; preview_color.innerHTML= rgb; preview_color.style.backgroundColor = rgb; }; </script> Try it Yourself
🌐
Medium
medium.com › @dianagureev › hex-rgb-converter-on-javascript-e6f4daadce5f
HEX-RGB Converter on JavaScript. My Google Doc with this article is… | by Diana Gureev | Medium
November 11, 2023 - I will go through the loop to check each RGB element in the array. To check if it is only one digit, I retrieve values from my Hexadecimal Number System object as an array of string and check if it includes the element.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-create-a-hex2rgb-color-converter-ce32d32afd1f
Diving into JavaScript: How to Create a Hex2RGB Color Converter
January 22, 2019 - Sett the body’s background color to the input value. Check the color contrast and change the text color accordingly. Call the convert function and place the converted color into the RGB input field.
Find elsewhere
🌐
Medium
medium.com › @hoanganhlam › convert-hex-to-rgb-in-javascrip-15d428176273
Convert Hex to RGB in Javascript
June 6, 2018 - In this tutorial, I’m going to help you convert hex color to RGB color using javascript. You can later integrate as a function into any…
🌐
LabEx
labex.io › tutorials › javascript-convert-hexadecimal-to-rgb-string-28375
Hex to RGB Conversion | JavaScript | Color Manipulation | LabEx
If the color code is 3-digits, first convert it to the 6-digit version. If an alpha value is provided alongside the 6-digit hex, return an rgba() string.
🌐
YouTube
youtube.com › leanne r
Convert hex to rgb in Javascript with TinyColor - YouTube
In this video, I show you how to make a quick and easy app which converts hex colors to rgb using the TinyColor library. ✨Contents: ✨00:26 - Setting up the H...
Published: October 22, 2021
Views: 861
🌐
CodePen
codepen.io › othmanDes › pen › VWRLrP
Hex To Rgb Color Convert With Javascript
<div id="hex2rgb"> <h4>Hex To Rgb Convert</h4> <form> <label>Color Format : #F5CD14</label> <input type="text" id="hex-color" placeholder="Hex"> <button type="button" id="convert" onclick=(hex2rgb())>Convert</button> <input type="text" id="rgb-color" placeholder="Rgb"> </form> </div> !
🌐
YouTube
youtube.com › watch
How to Convert Hex to RGB Color Format in Javascript - YouTube
In this video, you will learn how to convert hex to rgb color format in javascript. I hope you'll like the video and leave your feedback and suggestions for ...
Published: April 26, 2024
🌐
QuickRef.ME
quickref.me › home › how to convert hex to rgb in javascript - quickref.me
How to convert hex to rgb in JavaScript - QuickRef.ME
In this Article we will go through how to convert hex to rgb only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
🌐
Nimish Prabhu
nimishprabhu.com › home › convert rgb to hex and hex to rgb using javascript (online demo)
Convert RGB to HEX and HEX to RGB using Javascript (Online Demo)
October 27, 2020 - That’s it, we have completed HEX to RGB conversion as well. Here are ready to use Javascript functions to convert HEX color value to RGB color value and RGB color value to HEX color value.
🌐
JavaScript in Plain English
javascript.plainenglish.io › convert-hex-to-rgb-with-javascript-4984d16219c3
Convert HEX to RGB with JavaScript | by Andreas Zettl | JavaScript in Plain English
October 11, 2020 - String.prototype.convertToRGB = function(){ if(this.length != 6){ throw "Only six-digit hex colors are allowed."; } var aRgbHex = this.match(/.{1,2}/g); var aRgb = [ parseInt(aRgbHex[0], 16), parseInt(aRgbHex[1], 16), parseInt(aRgbHex[2], 16) ]; return aRgb; } console.log('1502BE'.convertToRGB()); console.log('ff0000'.convertToRGB()); console.log('f00'.convertToRGB()); [21, 2, 190] [255, 0, 0] Only six-digit hex colors are allowed. Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel! ... New JavaScript and Web Development content every day.
🌐
FrontendGeek
frontendgeek.com › blogs › how-to-convert-hex-to-rgb-in-javascript
How to convert HEX to RGB in JavaScript
July 6, 2026 - For example, RGB(255, 0, 0) also represents the color red. Converting HEX to RGB involves extracting the red, green, and blue values from the HEX color and converting them to their decimal equivalents.
🌐
Javascript
javascript.nexus › posts › converting-hex-to-rgb-and-rgb-to-hex
Converting hex to RGB and RGB to hex | Javascript Nexus
July 22, 2023 - const hex = '#FDAADD'.substr(1); const first = hex.substring(0, 2); const second = hex.substring(2, 4); const third = hex.substring(4); const rgb = `rgb(${parseInt(first, 16)},${parseInt(second, 16)},${parseInt(third, 16)})`; Check out your result with this little converter I’ve made 👇 ... This article wouldn’t be complete if we did not go the opposite direction by converting RGB to HEX.
🌐
YouTube
youtube.com › watch
RGB To HEX / Hex To RGB Converter With Javascript - YouTube
Create a RGB-HEX converter that converts hex color code to rgb and rgb code to hex. An intermediate level project that uses HTML, CSS & Javascript.📁 Downloa...
Published: August 3, 2021
🌐
npm
npmjs.com › package › hex-rgb
hex-rgb - npm
May 3, 2021 - Convert HEX color to RGBA. Latest version: 5.0.0, last published: 5 years ago. Start using hex-rgb in your project by running `npm i hex-rgb`. There are 239 other projects in the npm registry using hex-rgb.
      » npm install hex-rgb
    
Published: May 03, 2021
Version: 5.0.0
🌐
CSS-Tricks
css-tricks.com › converting-color-spaces-in-javascript
Converting Color Spaces in JavaScript | CSS-Tricks
January 26, 2021 - I like that this shows the math ... do the hex-to-decimal conversion in Javascript: using parseInt with a base parameter. For example, parseInt('FF',16) will return the integer 255.