In daily development, values in different formats are often converted to each other. The following provides a solution.
Copy codeThe Code is as follows:
// Regular Expression of hexadecimal color value
Var reg =/^ # ([0-9a-fA-f] {3} | [0-9a-fA-f] {6}) $ /;
/* Convert RGB color to hexadecimal format */
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 <aColor. length; 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 <aNum. length; I + = 1 ){
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;
}
// Process the six-digit color value
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 the color conversion method:
Copy codeThe Code is as follows:
Ar sRgb = "RGB (23,245, 56)", sHex = "# 34538b ";
Var sHexColor = sRgb. colorHex ();
Var sRgbColor = sHex. colorRgb ();