1function rgbToHex(r, g, b) {
2 return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
3}
4
5function hexToRgb(hex) {
6 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
7 if(result){
8 var r= parseInt(result[1], 16);
9 var g= parseInt(result[2], 16);
10 var b= parseInt(result[3], 16);
11 return r+","+g+","+b;//return 23,14,45 -> reformat if needed
12 }
13 return null;
14}
15console.log(rgbToHex(10, 54, 120)); //#0a3678
16console.log(hexToRgb("#0a3678"));//"10,54,120"
1function hexToRgb(hex){
2 var result = /^#?([a-f\d]{2}])([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
3
4 return result ? {
5 r: parseInt(result[1], 16);
6 g: parseInt(result[2], 16);
7 b: parseInt(result[3], 16);
8 } : null;
9}
10var hex = "#0a3678";
11console.log(hexToRgb(hex).r+","+hexToRgb(hex).g+","+hexToRgb(hex).b);//10,54,120
1function hexToRgb(hex) {
2 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
3 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
4 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
5 return r + r + g + g + b + b;
6 });
7
8 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
9 return result ? [
10 parseInt(result[1], 16),
11 parseInt(result[2], 16),
12 parseInt(result[3], 16)
13 ] : null;
14}
15
16alert(hexToRgb("#0033ff").g); // "51";
17alert(hexToRgb("#03f").g); // "51";