Last active
July 18, 2022 10:25
-
-
Save whitlockjc/9363016 to your computer and use it in GitHub Desktop.
Use JavaScript to Convert RGBA CSS Value to Hexadecimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
} |
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);
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.
Thanks!
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
Sometimes yields 7-letter HEX values, eg.
#fafa0ff
.