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

Changing hex codes to rgb values with JavaScript - Stack Overflow
Can someone explain to me how I would convert a hex code, ex: #FF9C19, to an rgb value, corresponding ex: (255, 156, 25), or the other way around using JavaScript? I found a post that asked this ... More on stackoverflow.com
🌐 stackoverflow.com
[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
🌐
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.
🌐
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.
🌐
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
🌐
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.
🌐
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.
🌐
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
🌐
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.
🌐
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.
🌐
GitHub
gist.github.com › xenozauros › f6e185c8de2a04cdfecf
Javascript: HEX to RGB to HSL · GitHub
function hexToCssHsl(hex, valuesOnly = false) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); var r = parseInt(result[1], 16); var g = parseInt(result[2], 16); var b = parseInt(result[3], 16); var cssString = ''; r /= 255, ...
Top answer
1 of 2
5
  1. Hex codes use base 16 (hexadecimal), RGB uses base 10 (decimal)
  2. Hex codes can be split into 3 bytes which describe red RR, green GG then blue BB, i.e. #RRGGBB
  3. The # for hex isn't always written, or sometimes it may use 0x or &h etc instead (you may need to consider this depending on your envionment)

Putting these together and using a RegExp to extract the interesting bits and parseInt to convert from the String representation of the base 16 numbers

function hex_to_RGB(hex) {
    var m = hex.match(/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i);
    return {
        r: parseInt(m[1], 16),
        g: parseInt(m[2], 16),
        b: parseInt(m[3], 16)
    };
}
// ex.
hex_to_RGB('#FF0110') // {r: 255, g: 1, b: 16}

When converting in the opposite direction you would use num.toString(16) and don't forget to pad the bytes with a '0' if they're smaller than (dec) 16


If you're starting with an Integer i which represents your hex colour, you can access the RGB values using bitwise operations, i.e.

var i = 0xFF0110, // 16711952
    rgb = {
        r: (i >> 16) & 0xFF,        // or `(i & 0xFF0000) >> 16`
        g: (i >>  8) & 0xFF,        // or `(i & 0x00FF00) >>  8`
        b:  i        & 0xFF         // or ` i & 0x0000FF       `
    }; // {r: 255, g: 1, b: 16}, same as before
2 of 2
3

A legal hex color can be 3 or 6 characters after the '#', and rgb components

can be either percentages or numbers between 0 and 255.

function hexToRgb(c){
    if(/^#([a-f0-9]{3}){1,2}$/.test(c)){
        if(c.length== 4){
            c= '#'+[c[1], c[1], c[2], c[2], c[3], c[3]].join('');
        }
        c= '0x'+c.substring(1);
        return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
    }
    return '';
}

function rgbToHex(rgb){
    var c= rgb.match(/\d+(\.\d+)?%?/g);
    if(c){
        c= c.slice(0, 3).map(function(next){
            var itm= next;
            if(itm.indexOf('%')!= -1){
                itm= Math.round(parseFloat(itm)*2.55);
            }
            if(itm<0) itm= 0;
            if(itm>255) itm= 255;
            itm= Math.round(itm).toString(16);
            if(itm.length== 1) itm= '0'+itm;
            return itm;
        });
        return '#'+c.join('').toLowerCase();
    }
    return '';
}