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";
1export const hexToRgb = (h: string, isPct: boolean) => {
2 let r: string = '0', g: string = '0', b: string = '0';
3 isPct = isPct === true;
4
5 if (h.length == 4) {
6 r = "0x" + h[1] + h[1];
7 g = "0x" + h[2] + h[2];
8 b = "0x" + h[3] + h[3];
9
10 } else if (h.length == 7) {
11 r = "0x" + h[1] + h[2];
12 g = "0x" + h[3] + h[4];
13 b = "0x" + h[5] + h[6];
14 }
15
16 if (isPct) {
17 r = (parseInt(r) / 255 * 100).toFixed(1).toString();
18 g = (parseInt(g) / 255 * 100).toFixed(1).toString();
19 b = (parseInt(b) / 255 * 100).toFixed(1).toString();
20 }
21
22 return "rgb(" + (isPct ? r + "%," + g + "%," + b + "%" : +r + "," + +g + "," + +b) + ")";
23}