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 componentToHex(c) {
2 var hex = c.toString(16);
3 return hex.length == 1 ? "0" + hex : hex;
4}
5
6function rgbToHex(r, g, b) {
7 return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
8}
9
10alert(rgbToHex(0, 51, 255)); // #0033ff