Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active December 12, 2015 00:59
Show Gist options
  • Save zeusdeux/4688010 to your computer and use it in GitHub Desktop.
Save zeusdeux/4688010 to your computer and use it in GitHub Desktop.
This gist adds two methods HexToRGB() and RGBToHex() to String and Array prototypes in JavaScript.
String.prototype.hexToRGB = function(){
if (this[0] === "#" && this.length === 7){
return String.prototype.hexToRGB.call(this.slice(1));
}
if (!/^[a-fA-F\d]{6}$/.test(this) || this.length > 6){
throw new SyntaxError("String is not a valid hex number");
}
var str = "(";
for (var i=0; i<=this.length-2; i+=2){
str+=(parseInt(this.substr(i,2),16));
if( i !== this.length-2) {
str+=",";
}
}
return str+")";
}
String.prototype.rgbToHex = function (){
var temp = this;
if(this[0] === "(" && this[this.length-1] === ")") {
temp = this.slice(1,this.length-1);
}
temp = temp.split(",");
if (temp.length !== 3){
throw "String is not RGB";
}
return temp.rgbToHex();
}
Array.prototype.rgbToHex = function (){
var str = "";
for (var i=0; i<this.length; i++) {
str+=((parseInt(this[i],10) <= 255 ? parseInt(this[i],10) : eval('throw new SyntaxError("String ("+parseInt(this[i],10)+") is not a valid hex number")')).toString(16));
}
return str;
}
/* Examples */
/* "#ffffff".HexToRGB() gives "(255,255,255)" */
/* "ffffef".HexToRGB() gives "(255,255,239)" */
/* "(255,255,239)".RGBToHex() gives "ffffef" */
/* "255,255,239".RGBToHex() gives "ffffef" */
/* [255,255,239].RGBToHex() gives "ffffef" */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment