Posted By

Sverri on 07/28/10


Tagged

hex Converter RGB


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jackkeller


HEX to RGB Converter


 / Published in: JavaScript
 

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

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.

  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>");

Report this snippet  

You need to login to post a comment.