I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.
Just comment out the regex line if you know what you're doing and it's a tiny bit faster.
function hexToRGBA(hex, alpha){
hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
var b_int = parseInt(hex, 16);
return "rgba("+[
(b_int >> 16) & 255, //R
(b_int >> 8) & 255, //G
b_int & 255, //B
alpha || 1 //add alpha if is set
].join(",")+")";
}
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Use these Function to achive the result without any issue. :)
One-line functional HEX to RGBA
Supports both short
#fff
and long#ffffff
forms.Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.
examples:
I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.
Just comment out the regex line if you know what you're doing and it's a tiny bit faster.
My version of hex2rbg:
String.replace, String.split, String.match
etc..you may need remove hex.trim() if you are using IE8.
e.g.
code:
Use these Function to achive the result without any issue. :)
HTML use the hexadecimal system and the rgb uses the decimal system. so you have to convert the number from hexadecimal to decimal and vice versa.
// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-
// Hex can be 3 values or 6.
// Rgb can be percentages as well as integer values.
// Best to account for all of these formats, at least.