Skip to content

Instantly share code, notes, and snippets.

@whitlockjc
Last active July 18, 2022 10:25
Show Gist options
  • Save whitlockjc/9363016 to your computer and use it in GitHub Desktop.
Save whitlockjc/9363016 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 inParts = rgba.substring(rgba.indexOf("(")).split(","),
r = parseInt(trim(inParts[0].substring(1)), 10),
g = parseInt(trim(inParts[1]), 10),
b = parseInt(trim(inParts[2]), 10),
a = parseFloat(trim(inParts[3].substring(0, inParts[3].length - 1))).toFixed(2);
var outParts = [
r.toString(16),
g.toString(16),
b.toString(16),
Math.round(a * 255).toString(16).substring(0, 2)
];
// Pad single-digit output values
outParts.forEach(function (part, i) {
if (part.length === 1) {
outParts[i] = '0' + part;
}
})
return ('#' + outParts.join(''));
}
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);
}
@manuelQuiroz
Copy link

You have to make a small change in the part of the method substring()

return ('#' + r.toString(16) + g.toString(16) + b.toString(16) + (a * 255).toString(16)).substring(0, 7);

@bendaly818
Copy link

This is incorrect for r,g,b,a values which result in a string of length 1 when toString(16) is called on them.

e.g rgba(255, 15, 255, 255) => #fffffff which should actually be #ff0fffff.

To fix this you will need to add a leading 0 to any value r,g,b or a which is length 1.

@whitlockjc
Copy link
Author

Thanks!

@whitlockjc
Copy link
Author

I have made changes to fix the comments above (I hope).

cc/ @bendaly818, @manuelQuiroz and @knutole

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