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 // 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";
1function hexToRgb(hex) {
2 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
3 return result ? {
4 r: parseInt(result[1], 16),
5 g: parseInt(result[2], 16),
6 b: parseInt(result[3], 16)
7 } : null;
8}
9
10alert(hexToRgb("#0033ff").g); // "51";
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