Graham Walters

A wee site for the things I do

How to convert RGB to Hex Color

While writing my mapping tool I stumbled upon the problem that jQuery passes rgb values back from the .css('color') call. My solution was to write a function which would parse the response and respond with a hex color value. I also added a feature where the function accepts a boolean value for ‘hash’. If hash is true, the function returns the hex value with a # symbol in front of the value.

Here is the function with a line by line explanation below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * Convert jQuery color response (rgb) to hex color
 * @param rgb - color
 * @param hash - Boolean for: Add the hash symbol to the front of the response
 */
function RGBtoHEX(rgb, hash) {
  var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  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];
  }
  return (hash == true ? '#' : '') + parts.join('').toUpperCase();
}
  • Lines 1-6 simply declares the JavaScript function.
  • Line 7 we split split the rgb value into seperate parts (an array called parts).
  • Line 8 we delete the first part (parts[0]) as it is just the original rgb string.
  • Line 9 we loop through the parts (1-3).
  • Line 10 we convert each part to its hex value.
  • Line 11 we check how long the hex value is, and if it is 1 character long, we pad it with a 0 in front.
  • Line 12 we close the for loop.
  • Line 13 we join each of the parts, and if hash is true we return the parts with a # symbol in front of the parts.

This entry was tagged Color Hex jQuery RGB