Topic description
Convert the rgb color string to hexadecimal form, such as rgb(255, 255, 255) to #ffffff
1. The number of spaces after each in rgb is not fixed
2. The hexadecimal expression uses six 3. If the input is not in rgb format, return the original input
code
1 function rgb2hex(sRGB) {
2 var rgb = /rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/ ;
3 var rgbArr = sRGB .match(rgb); // rgbArr = {rgb(255, 255, 255),255,255,255}
4 /* var rgb = /rgb\((\d+)\s*,\s*(\d+)\s* ,\s*(\d+)\)/g
5 //rgb = {rgb(255, 255, 255)} */
6 var str = "#"; // color value
7 if (!rgbArr){ // Does not match regular match
8 return sRGB;
9 }
10 else {
11 for ( vari = 1 ; i<4; i++ ){
12 var rgbIndex = parseInt(rgbArr[i]);
13 if (rgbIndex<16 && rgbIndex>=0 ){
14 str += ('0'+rgbIndex.toString(16 )); // keep two digits
15 }
16 else if (rgbIndex>=16 && rgbIndex<=255 ){
17 str += rgbIndex.toString(16 );
18 }
19 else {
20 return sRGB; // not a color value character
21 }
22 }
23 return str;
24 }
25 }
Source: Niuke.com