Convert rgb strings to hex in Javascript

Neil picture Neil · Oct 25, 2012 · Viewed 23.8k times · Source

I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always in the form of a string:

"rgb(255,255,255)"

How can that be converted in to a hex number like:

0xffffff

Answer

Nippey picture Nippey · Oct 25, 2012

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("");