1f7e Trending Us » Blog Archive » Javascript – RGB to Hexadecimal Color Converter
logo

While working on a side project today, I found the need for an RGB to hex color code converter in javascript. There are a number out there within a couple of easy Google searches, but I wasn’t happy with any of the ones that I found.

Every example I found other people had posted over the years involves using a string using 0-9, a-f and then using character matching and some math shifting to return a hex conversion. This irked me because javascript is perfectly capable of doing these conversions with native methods.

So what you will run into from time to time is that some browsers like Firefox and Safari return the css color value of an element as an RGB format, like RGB(204,0,0). Other browsers, namely Internet Explorer, return the hex code, like #cc0000.

What I wanted was a reusable method that will convert an RGB value to the equivalent hex number. It also had to be flexible enough to not be abused if I pass in a hex or non-RGB value. This helps it play nicely across different browsers. Its using native javascript “parseInt” and “toString” methods to do the converting. So enough chit-chat, here’s the damn code. =)

rgbhex = function(rgbval){
var s = rgbval.match(/rgb\s*\x28((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*,\s*((?:25[0-5])|(?:2[0-4]\d)|(?:[01]?\d?\d))\s*\x29/);

var d='',e;
if(s){ s=s.splice(1); }
	if(s && s.length==3){
		d='';
		for(i in s){
			e=parseInt(s[i],10).toString(16);
			e == "0" ? d+="00":d+=e;
		} return '#'+d;
	}else{ return rgbval; }
}

0