HEX to RGB Converter


/ Published in: JavaScript
Save to your folder(s)

Converts and returns the RGB equivalent of a HEX value. The RGB values are returned as an object, with the members "red", "green" and "blue". See the example in code snippet if you do not know how to use the function.


Copy this code and paste it in your HTML
  1. function hex2rgb(hex) {
  2. if (hex[0]=="#") hex=hex.substr(1);
  3. if (hex.length==3) {
  4. var temp=hex; hex='';
  5. temp = /^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(temp).slice(1);
  6. for (var i=0;i<3;i++) hex+=temp[i]+temp[i];
  7. }
  8. var triplets = /^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(hex).slice(1);
  9. return {
  10. red: parseInt(triplets[0],16),
  11. green: parseInt(triplets[1],16),
  12. blue: parseInt(triplets[2],16)
  13. }
  14. }
  15.  
  16. // Example
  17. var hex = "#fA0";
  18. var rgb = hex2rgb(hex);
  19. document.write("<pre>"+hex+" \u2192 rgb("+rgb.red+","+rgb.green+","+rgb.blue+")</pre>");

URL: http://sverri.tumblr.com/post/865857181/javascript-hex-to-rgb-converter

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.