Background-color hex to JavaScript variable

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:

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/

Example output:

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

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);

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

Leave a Comment