/ Published in: JavaScript
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function hex2rgb(hex) { if (hex[0]=="#") hex=hex.substr(1); if (hex.length==3) { var temp=hex; hex=''; temp = /^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(temp).slice(1); for (var i=0;i<3;i++) hex+=temp[i]+temp[i]; } var triplets = /^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(hex).slice(1); return { red: parseInt(triplets[0],16), green: parseInt(triplets[1],16), blue: parseInt(triplets[2],16) } } // Example var hex = "#fA0"; var rgb = hex2rgb(hex); 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