Retrieve Hex Code of RGB format color to avoid cross browser back color issue

At times we need to calculate the equivalent hexadecimal code of the RGB color format to avoid cross-browser compatibility issue. For instance, you want to get the background-color of elements but the result is different for each browser.

E.g.

When you try to get the backcolor of the above given div using JavaScript, the result would be different for different browsers.

Internet Explorer : #FEFEEE

Mozila Firefox : rgb(254,254,238)

Google Chrome : rgb(254,254,238)

But if you want to have the uniform result the following code may help you :

This function will check for the presence of rgb in your color code & return the equivalent hex code & on the default it will return some default color,

Input –> rgb(254,254,238)
Output –> #FEFEEE 

// return the hex format of the color.

function rgbToHex(color)

{

// Check if it is already present in hexadecimal format or not.

if (color.substr(0, 1) === '#')

{

return color;

}

 

// Check either it content the rgb color format or not

else if (color.indexOf('rgb') > 0)

{

var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

var red = parseInt(digits[2]);

var green = parseInt(digits[3]);

var blue = parseInt(digits[4]);

var rgb = blue | (green
150 150 Burnignorance | Where Minds Meet And Sparks Fly!