In daily development, conversion between color range values in different formats is often used. A solution is given below.
//Regular expression for hexadecimal color value
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
/*Convert RGB color to hexadecimal*/
String.prototype.colorHex = function(){
var that = this;
If(/^(rgb|RGB)/.test(that)){
var aColor = that.replace(/(?:(|)|rgb|RGB)*/g,"").split(",");
var strHex = "#";
for(var i=0; i
var hex = Number(aColor).toString(16);
if(hex === "0"){
Hex = hex;
}
strHex = hex;
}
If(strHex.length !== 7){
strHex = that;
}
return strHex;
}else if(reg.test(that)){
var aNum = that.replace(/#/,"").split("");
If(aNum.length === 6){
return that;
}else if(aNum.length === 3){
var numHex = "#";
for(var i=0; i
numHex = (aNum aNum);
}
return numHex;
}
}else{
return that;
}};
/*Convert hexadecimal color to RGB format*/
String.prototype.colorRgb = function(){
var sColor = this.toLowerCase();
If(sColor && reg.test(sColor)){
If(sColor.length === 4){
var sColorNew = "#";
for(var i=1; i<4; i =1){
sColorNew = sColor.slice(i,i 1).concat(sColor.slice(i,i 1));
}
sColor = sColorNew;
}
//Processing six-digit color values
var sColorChange = [];
for(var i=1; i<7; i =2){
sColorChange.push(parseInt("0x" sColor.slice(i,i 2)));
}
return "RGB(" sColorChange.join(",") ")";
}else{
return sColor;
}};
Use color conversion method: