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";
1hexToRGB(hex: string, alpha: string) {
2
3 const r = parseInt(hex.slice(1, 3), 16);
4 const g = parseInt(hex.slice(3, 5), 16);
5 const b = parseInt(hex.slice(5, 7), 16);
6
7 if (alpha) {
8 return `rgba(${r}, ${g}, ${b}, ${alpha})`;
9 } else {
10 return `rgb(${r}, ${g}, ${b})`;
11 }
12}
1//If you write your own code, remember hex color shortcuts (eg., #fff, #000)
2
3function hexToRgbA(hex){
4 var c;
5 if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
6 c= hex.substring(1).split('');
7 if(c.length== 3){
8 c= [c[0], c[0], c[1], c[1], c[2], c[2]];
9 }
10 c= '0x'+c.join('');
11 return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
12 }
13 throw new Error('Bad Hex');
14}
15
16hexToRgbA('#fbafff')
17
18/* returned value: (String)
19rgba(251,175,255,1)
20*/
21
1function rgba2hex(rgba) {
2 rgba = rgba.match(
3 /^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i
4 );
5 return rgba && rgba.length === 4
6 ? "#" +
7 ("0" + parseInt(rgba[1], 10).toString(16)).slice(-2) +
8 ("0" + parseInt(rgba[2], 10).toString(16)).slice(-2) +
9 ("0" + parseInt(rgba[3], 10).toString(16)).slice(-2)
10 : "";
11}
12// examples
13console.log(rgba2hex('rgba(240, 240, 240, 0.5)'));
14console.log(rgba2hex('rgba(40, 20, 80, 1.0)'));