Using javascript to Convert HEX and RGB formats

Source: Internet
Author: User

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 ();

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.