Convert rgb strings to hex in Javascript
I would at first cut away the CSS parts:
var a = "rgb(255,255,255)".split("(")[1].split(")")[0];
Then split it into separate numbers:
a = a.split(",");
Convert the single numbers to hex
var b = a.map(function(x){ //For each array element
x = parseInt(x).toString(16); //Convert to a base16 string
return (x.length==1) ? "0"+x : x; //Add zero if we get only one character
})
And glue it back together:
b = "0x"+b.join("");
The following is adapted from a Colour
class I wrote and use but may be overkill for your needs since it handles percentages and negative numbers.
Demo: http://jsfiddle.net/5ryxx/1/
Code:
function componentFromStr(numStr, percent) {
var num = Math.max(0, parseInt(numStr, 10));
return percent ?
Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num);
}
function rgbToHex(rgb) {
var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
var result, r, g, b, hex = "";
if ( (result = rgbRegex.exec(rgb)) ) {
r = componentFromStr(result[1], result[2]);
g = componentFromStr(result[3], result[4]);
b = componentFromStr(result[5], result[6]);
hex = "0x" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
return hex;
}