Open In App

How to get hex color value of RGB value ?

Given the RGB color value and the task is to get the Hex Code of that color using JavaScript. 

Approach 1:



Example 1: This example gets the RGB value of white which is rgb(255,255,255) and converts it into HexCode by using JavaScript. 




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_UP">
</p>
  
<button onClick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    up.innerHTML = 'Click on button to hex code of the color';
      
    function convert(rgb) {
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
      
        function hexCode(i) {
            return ("0" + parseInt(i).toString(16)).slice(-2);
        }
        return "#" + hexCode(rgb[1]) + hexCode(rgb[2])
                + hexCode(rgb[3]);
    }
      
    function GFG_Fun() {
        down.innerHTML = "Hex Code of 'white' = "
            + convert('rgb(255,255,255)');
    }
</script>

Output:



How to get hex color value of RGB value ?

Example 2: This methods first checks, if hex value is provided instead of RGB value. Because some browsers return the hex value in place of the RGB value. This example gets the RGB value of green which is RGB(0,128,0) and converts it into HexCode by creating a function. 




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<p id="GFG_UP">
</p>
  
<button onClick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN"></p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    up.innerHTML = 'Click on button to hex code of the color';
      
    function convert(rgb) {
        if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
      
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
      
        function hexCode(i) {
            return ("0" + parseInt(i).toString(16)).slice(-2);
        }
        return "#" + hexCode(rgb[1]) + hexCode(rgb[2])
                + hexCode(rgb[3]);
    }
      
    function GFG_Fun() {
        down.innerHTML = "Hex Code of 'Green' = "
                + convert('rgb(0,128,0)');
    }
</script>

Output:

How to get hex color value of RGB value ?


Article Tags :