/**
* RGB VALUES TO HEX COLOUR CODE
* Set values as separate function parameter
*/
function rgb2hex(){
// Open hex string
var retval = '#';
// Loop args up to 3 (R, G and B)
for(var i = 0; i < arguments.length && i < 3; i++){
// Type validation
if(typeof arguments[i] !== 'number'){ return false; }
// Double form creation for single digit hex numbers
if(arguments[i] < 16){ retval += 0; }
// Append converted base
retval += arguments[i].toString(16);
}
return retval;
}
console.log(rgb2hex(255, 255, 255));
console.log(rgb2hex(230, 127, 94));
console.log(rgb2hex(0, 0, 0));
/**
* HEX COLOUR CODE TO RGB ARRAY
* h = hex code
*/
function hex2rgb(h){
var ret = [],
form = 2;
// Pattern matching
if(!h.match(/^#?[a-fA-F0-9]{3,6}$/ig)){
return false;
}
h = h.replace(/[^a-fA-F0-9]+/ig, '');
// Validate short form
if(h.length == 6){
form = 2; // Full 6 char form
}else if(h.length == 3){
form = 1; // Short 3 char form
}else{
return false; // Not a valid form
}
// Loop string on form base
for(var i = 0; i < h.length; i += form){
// Form double string build
var d;
if(form == 2){
d = h[i] + '' + h[i+1];
}else{
d = h[i] + '' + h[i];
}
// Set converted number in array
ret[i/form] = parseInt(d, 16);
}
return ret;
}
console.log(hex2rgb('#fff'));
console.log(hex2rgb('#e67f5e'));
console.log(hex2rgb('#000000'));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.