Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Last active January 24, 2018 14:32
Show Gist options
  • Save Rycochet/8597336 to your computer and use it in GitHub Desktop.
Save Rycochet/8597336 to your computer and use it in GitHub Desktop.
Javascript hex to rgb()/rgba()
// Please note this uses my Math.range and String.regex methods
/**
* Convert a hex colour to a rgb/rgba value
* @param {string} hex
* @param {?number} opacity
* @returns {string}
*/
function rgba(hex, opacity) {
var colours = hex.regex(/#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})/i).map(function(val) {
return Math.range(0, parseInt(val, 16), 255);
}).join(",");
if (opacity === undefined) {
return "rgb(" + colours + ")";
}
return "rgba(" + colours + "," + opacity + ")";
}
@pertrai1
Copy link

Where does the range method come from? I can't find it in the documents for Math

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment