How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
For 3 digits hexToRgb function of Tim Down can be improved as below:
var hex2Rgb = function(hex){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
return result ? {
r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
toString: function() {
var arr = [];
arr.push(this.r);
arr.push(this.g);
arr.push(this.b);
return "rgb(" + arr.join(",") + ")";
}
} : null;
};