This article mainly introduces the conversion between the hexadecimal color value (HEX) and the RGB format in javascript, and uses the regular method to convert the RGB color to the hexadecimal color, you can refer to the conversion between different formats of Color domain values in daily development. Here is a solution.
The 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 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;
}
// 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:
The Code is as follows:
Ar sRgb = "RGB (23,245, 56)", sHex = "# 34538b ";
Var sHexColor = sRgb. colorHex ();
Var sRgbColor = sHex. colorRgb ();