Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following will do to the RGB to hex conversion and add any required zero padding: </p> <pre><code>function componentToHex(c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } alert( rgbToHex(0, 51, 255) ); // #0033ff </code></pre> <p>Converting the other way:</p> <pre><code>function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert( hexToRgb("#0033ff").g ); // "51"; </code></pre> <p>Finally, an alternative version of <code>rgbToHex()</code>, as discussed in @casablanca's answer and suggested in the comments by @cwolves:</p> <pre><code>function rgbToHex(r, g, b) { return "#" + ((1 &lt;&lt; 24) + (r &lt;&lt; 16) + (g &lt;&lt; 8) + b).toString(16).slice(1); } </code></pre> <h2>Update 3 December 2012</h2> <p>Here's a version of <code>hexToRgb()</code> that also parses a shorthand hex triplet such as "#03F":</p> <pre><code>function hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert( hexToRgb("#0033ff").g ); // "51"; alert( hexToRgb("#03f").g ); // "51"; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload