How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
This snippet converts hex to rgb and rgb to hex.
View demo
function hexToRgb(str) {
if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) {
var hex = str.substr(1);
hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
var rgb = parseInt(hex, 16);
return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
}
return false;
}
function rgbToHex(red, green, blue) {
var out = '#';
for (var i = 0; i < 3; ++i) {
var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
if (isNaN(n) || n < 0 || n > 255) {
return false;
}
out += (n < 16 ? '0' : '') + n.toString(16);
}
return out
}