In a previous article, I have mentioned Using Google Translate to translate language using HTML- Javascript now in this article, I have mentioned code to convert RGB to Hex and Hex to RGB using javascript easily and quickly.

RGB to Hex using Javascript

Converting RGB into Hex using Javascript is very simple and straighr forward, we get each r,g, and b values and convert it into int using parseInt then, use .toString(16) to get hex values, as shown below in JS function.

function RGBToHex() {
  var r = document.Form1.R.value;
  var g = document.Form1.G.value;
  var b = document.Form1.B.value;
  r = parseInt(r).toString(16);
  g = parseInt(g).toString(16);
  b = parseInt(b).toString(16);

  if (r.length == 1)
    r = "0" + r;
  if (g.length == 1)
    g = "0" + g;
  if (b.length == 1)
    b = "0" + b;

  return "#" + r + g + b;
}

In the above JS function we are also appending "0" at start, when any of the r,g,b digit count is "1".

Here is the fiddle for it

Hex to RGB using Javascript

We can convert hex to RGB, by getting substring values for Red, Green and Blue, like if hexcode is #0077BB, then we will get substring "00" for R and then use parseInt() to get the Red value.

Similary, we will perform these operations for Green and Blue.

Once we have got all the values, we will combine them to get color and we can return it as css color "rgb(0, 119, 187)", so here the complete Javascript code for it.

                 function calc() 
		{
                        var r,g,b,a="";
			var hex = document.getElementById("hex").value;
			if( hex=="" ) hex="000000";
			if( hex.charAt(0)=="#" ) hex=hex.substring(1,hex.length);
			if( hex.length!=6 && hex.length!=8 && hex.length!=3 )
			{
				alert("Please enter 6 digits color code !");
				return;
			}
			if( hex.length==3 )
			{
				r = hex.substring(0,1);
				g = hex.substring(1,2);
				b = hex.substring(2,3);
				r=r+r;
				g=g+g;
				b=b+b;
			}
			else
			{
				r = hex.substring(0,2);
				g = hex.substring(2,4);
				b = hex.substring(4,6);
			}
			if( hex.length==8 )
			{
            a = hex.substring(6,8);
            a = (parseInt(a, 16)/255.0).toFixed(2);
         }
			r = parseInt(r, 16);
			g = parseInt(g, 16);
			b = parseInt(b, 16);
         var css="rgb("+r+", "+g+", "+b+")";
			if( hex.length==8 )
            css="rgba("+r+", "+g+", "+b+", "+a+")";

			return hex;
		}

We can also create a complete demo using HTML form and above code, so if your HTML code is as below


<form id="mainForm" name="mainForm" autocomplete="off">
   <div class="form-group">
      <label for="hex">Hex color code (#RRGGBB)</label>
      <input type="text" id="hex" name="hex" placeholder="000000" minlength="3" maxlength="8" class="form-control form-control-lg" autofocus>
   </div>
   <div class="form-group">
      <button type="button" title="Convert" class="btn btn-primary" onclick="calc()"> Convert</button>
   </div>
   <div class="form-group">
      <label for="r">Red color (R)</label>
      <input type="text" id="r" name="r" class="form-control form-control-lg" readonly>
   </div>
   <div class="form-group">
      <label for="g">Green color (G)</label>
      <input type="text" id="g" name="g" class="form-control form-control-lg" readonly>
   </div>
   <div class="form-group">
      <label for="b">Blue color (B)</label>
      <input type="text" id="b" name="b" class="form-control form-control-lg" readonly>
   </div>
   <div class="form-group">
      <label for="css">CSS color</label>
      <input type="text" id="css" name="css" class="form-control form-control-lg" readonly>
   </div>
   <div class="form-group">
      <label for="color">Color preview</label>
      <input type="text" id="color" name="color" class="form-control" style="height:70px; border:1px solid black" readonly>
   </div>
</form>

Then we can use above JS code with it and create Hex to RGB converter using Javascript.

Output:

hex-to-rgb-using-javascript-min.png

Here is the fiddle for it

Another method which we can use to convert Hex to RGB is using regex and for loop, which will use same logic to get two digit or 1 digit string from Hex and then use parseInt() to get Red,Green or Blue value.

But this method has fewer lines of code then above method

function hex2rgb(hex, opacity) {
        var h=hex.replace('#', '');
        h =  h.match(new RegExp('(.{'+h.length/3+'})', 'g'));

        for(var i=0; i<h.length; i++)
            h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);

        if (typeof opacity != 'undefined')  h.push(opacity);

        return 'rgba('+h.join(',')+')';
}

You may also like to read:

How to format JSON date into valid date using javascript or jquery?

Read CSV file in Javascript and HTML5 FileReader (Multiple ways)

How to get user location using Javascript / HTML5 Geolocation?

Datetime Format Regex (MM/dd/yyyy) Javascript

How to get client's IP address using javascript or jQuery

How can i display title or label on polygons on google map?

how to check if string is null or empty using jQuery or javascript?

RGB to Hex Converter Online

Hex to RGB Converter online