Skip to content

Instantly share code, notes, and snippets.

@bockoblur
Forked from phuonghd/rgbaToHex.js
Created January 10, 2018 15:07
Show Gist options
  • Save bockoblur/e2e8f65a68cc32196daa9f400b041373 to your computer and use it in GitHub Desktop.
Save bockoblur/e2e8f65a68cc32196daa9f400b041373 to your computer and use it in GitHub Desktop.
Use JavaScript to Convert RGBA CSS Value to Hexadecimal
#!/usr/bin/env node
// Takes an rgba() CSS value and converts it to its 8 digit hexadecimal value.
//
// Usage: ./rgbaToHex.js "{YOUR_RGBA_STRING}"
//
// Example: ./rgbaToHex.js "rgba(197, 200, 198, .2)" => #C5C8C633
function trim (str) {
return str.replace(/^\s+|\s+$/gm,'');
}
function rgbaToHex (rgba) {
var parts = rgba.substring(rgba.indexOf("(")).split(","),
r = parseInt(trim(parts[0].substring(1)), 10),
g = parseInt(trim(parts[1]), 10),
b = parseInt(trim(parts[2]), 10),
a = parseFloat(trim(parts[3].substring(0, parts[3].length - 1))).toFixed(2);
return ('#' + r.toString(16) + g.toString(16) + b.toString(16) + (a * 255).toString(16).substring(0,2));
}
if (process.argv.length >= 3) {
console.log(rgbaToHex(process.argv[2]));
} else {
console.log('You must supply an rgba() CSS string to convert. Example: rgba(197, 200, 198, .2)');
console.log('');
console.log('Usage: ./rgbaToHex.js "{YOUR_RGBA_STRING}"');
process.exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment