By Removed_account

2009-03-12 14:44:23 8 Comments

I'm kind of new to JavaScript and jQuery and now I'm facing a problem:

I need to post some data to PHP and one bit of the data needs to be the background color hex of div X.

jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable.

The CSS function seems to return a string like this rgb(0, 70, 255).

I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS).

So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow.

I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing.

Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?


@Fotios 2011-04-22 19:49:13

If you have jQuery available, this is the super-compact version that I just came up with.

var RGBtoHEX = function(color) {
  return "#"+$.map(color.match(/\b(\d+)\b/g),function(digit){
    return ('0' + parseInt(digit).toString(16)).slice(-2)

@oriadam 2017-06-20 14:51:54

Nowadays we don't even need jQuery for mapping. Here is the vanilla version: var RGBtoHEX = function(color) { return "#"+(color.match(/\b(\d+)\b/g).map(function(digit){ return ('0' + parseInt(digit).toString(16)).slice(-2) })).join(''); };

@nickf 2009-03-12 14:58:07

try this out:

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.

var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"

In response to the question in the comments below:

I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks.

I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this:


Example output:

var d = document.createElement('div'); = 'rgba( 255,  60, 50, 0)';


// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]

@lpfavreau 2009-03-12 15:06:12

+1 nice implementation with the the regex match, although I wonder if there's a constant space after the comma across all browsers

@Removed_account 2009-03-12 15:20:04

Well, this is the actual answer, thanks. However for me Ipfavreau's answer worked, since I'm just posting the background-color to create a css file with php.

@Matthew Crumley 2009-03-12 18:52:33

Wouldn't parts be ["rgb(0, 70, 255)","0","70","255"]?

@KyleFarris 2009-05-04 22:03:22

I love StackOverflow. Thanks, didn't want to figure this out myself. :-P

@Naftali aka Neal 2011-04-01 16:55:00

@nickf this doesnt seem to work in IE parts always comes back as null and has an error. i made a question on it:…

@JeffB 2011-09-13 21:23:25

@Neal or anyone else having that issue: In IE, jquery 1.4.4 returns the hex code instead of the rgb string. So parts is null because the regex doesn't match, which causes an error when parts is used. I had to add a check before the delete and return the original string if parts is null.

@fortuneRice 2011-09-25 04:57:46

@nickf this is great; I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks.

@fortuneRice 2011-09-25 05:25:11

I made this a question of its own…

@fortuneRice 2011-12-03 07:43:06

@nickf forgot to thank you for that from before. btw I added /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0|0\.\d+))?\)$/ the |0 near the end to check when alpha is just 0 and not 0.x

@nickf 2011-12-03 12:56:40

@fortuneRice i think it should be (1|0|0?\.d+), since .3 is valid.

@The Virtual Machinist 2011-08-09 04:23:01

Here you go, this will allow you to use $(selector).getHexBackgroundColor() to return the hex value easily :

$.fn.getHexBackgroundColor = function() {
    var rgb = $(this).css('background-color');
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);}
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);

@user558987 2011-04-20 07:54:42

A JavaScript class that accepts a string and tries to figure out a valid color out of it. Some accepted inputs are for example:

* rgb(0, 23, 255)
* #336699
* ffee66
* fb0
* red
* darkblue
* cadet blue

@Derek 朕會功夫 2012-07-05 23:31:45

ffee66 and fb0 are not valid colors in CSS. Maybe you should try it first.

@Mark Rhodes 2010-11-16 14:25:48

With JQuery..

var cssColorToHex = function(colorStr){
    var hex = '#';
    $.each(colorStr.substring(4).split(','), function(i, str){
        var h = ($.trim(str.replace(')',''))*1).toString(16);
        hex += (h.length == 1) ? "0" + h : h;
    return hex;

@Marco Demaio 2010-08-19 15:06:34

How about this solution, function stringRGB2HEX returns a copy of the input string where all occurencies of colors in the format "rgb(r,g,b)" have been replaced by the hex format "#rrggbb".

   //function for private usage of the function below
   //(declaring this one in global scope should make it faster rather than 
   //declaraing it as temporary function inside stringRGB2HEX that need to be
   //instantieted at every call of stringRGB2HEX
   function _rgb2hex(rgb_string, r, g, b) 
      //VERY IMPORTANT: by adding (1 << 24) we avoid 'rgb(0, 0, 0)' to be mistakenly converted into '#0'
      var rgb = (1 << 24) | (parseInt(r) << 16) | (parseInt(g) << 8) | parseInt(b); //same thing of: ( r + (256 * g) + (65536 * b) + 16777216)
      //toString(16) specify hex 16 radix, works only for numbers [source:]   
      return '#' + rgb.toString(16).substr(1); //substr(1) because we have to remove the (1 << 24) added above

   function stringRGB2HEX(string)
      if(typeof string === 'string')
         string = string.replace(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/g, _rgb2hex);
      return string;

This one converts also rgb colors in complex styles like background.

A style.background value like: "none no-repeat scroll rgb(0, 0, 0)" is easily converted into "none no-repeat scroll #000000" by simply doing stringRGB2HEX(style.background)

@Kevin.Riggen 2010-05-22 18:35:14

These solutions will fail in Chrome, as it returns an rgba(x,x,x,x) for background-color.

EDIT: This is not necessarily true. Chrome will still set backgrounds using rgb(), depending on what you are doing. Most likely as long as there is no alpha channel applied, Chrome will respond with rgb instead of rgba.

@Mottie 2009-07-29 02:32:28

I found another function awhile back (by R0bb13). It doesn't have the regex, so I had to borrow it from nickf to make it work properly. I'm only posting it because it's an interesting method that doesn't use an if statement or a loop to give you a result. Also this script returns the hex value with a # (It was needed by the Farbtastic plugin I was using at the time)

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);

// call the function: rgb( "rgb(0, 70, 255)" );
// returns: #0046ff

Note: The hex result from nickf's script should be 0046ff and not 0070ff, but no big deal :P

Update, another better alternative method:

function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return ("0" + parseInt(x).toString(16)).slice(-2);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);

@Marco Demaio 2010-08-21 09:41:16

I would rather move function hex(x) out of the scope of fucntion rgb2hex for performance improvement. Anyway it's a nice clean solution, thanks for sharing. Have a look at mine below, I would like your opinion.

@Amr Elgarhy 2010-01-11 14:38:40

I found this solution and i am using it in my project

@Marco Demaio 2010-08-19 14:32:58

The solution provided at the link is WRONG because converts "rgb(0, 0, 0)" into "#0" instead of "#000000", the reason is that the << operator does not shift bits if the value to shift is a zero.

@lpfavreau 2009-03-12 14:53:46

You can set a CSS color using rgb also, such as this:

background-color: rgb(0, 70, 255);

It is valid CSS, don't worry.

Edit: See nickf answer for a nice way to convert it if you absolutely need to.

@Anurag 2010-05-22 20:59:38

+1 - if the color has to be restored on some web page later on, then why do any work converting at all :)

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] Detecting an "invalid date" Date instance in JavaScript

  • 2009-08-30 11:34:40
  • orip
  • 823832 View
  • 1489 Score
  • 43 Answer
  • Tags:   javascript date

94 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6678459 View
  • 8258 Score
  • 94 Answer
  • Tags:   javascript arrays

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

3 Answered Questions

9 Answered Questions

[SOLVED] Why does HTML think “chucknorris” is a color?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

Sponsored Content