Convert hexadecimal color values (HEX) and RGB formats using javascript _ javascript tips-js tutorial

Source: Internet
Author: User
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 ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.