Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active May 18, 2022 17:58
Show Gist options
  • Save RadGH/c277f220cb41cd0c222f297bad0bbbf5 to your computer and use it in GitHub Desktop.
Save RadGH/c277f220cb41cd0c222f297bad0bbbf5 to your computer and use it in GitHub Desktop.
Javascript convert RGB and RGBA to Hex, any format
/**
* Convert RGB to Hex. Allows whitespace. If given hex, returns that hex. Alpha opacity is discarded.
* Supports formats:
* #fc0
* #ffcc00
* rgb( 255, 255, 255 )
* rgba( 255, 255, 255, 0.5 )
* rgba( 255 255 255 / 0.5 )
*/
function rgb_any_to_hex( orig ) {
var regex_hex, regex_trim, color, regex_rgb, matches, hex;
// Remove whitespace
regex_trim = new RegExp(/[^#0-9a-f\.\(\)rgba]+/gim);
color = orig.replace( regex_trim, ' ' ).trim();
// Check if already hex
regex_hex = new RegExp(/#(([0-9a-f]{1})([0-9a-f]{1})([0-9a-f]{1}))|(([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2}))/gi);
if ( regex_hex.exec( color ) ) {
return color;
}
// Extract RGB values
regex_rgb = new RegExp( /rgba?\([\t\s]*([0-9]{1,3})[\t\s]*[, ][\t\s]*([0-9]{1,3})[\t\s]*[, ][\t\s]*([0-9]{1,3})[\t\s]*([,\/][\t\s]*[0-9\.]{1,})?[\t\s]*\);?/gim );
matches = regex_rgb.exec( orig );
if ( matches ) {
hex =
'#' +
(matches[1] | 1 << 8).toString(16).slice(1) +
(matches[2] | 1 << 8).toString(16).slice(1) +
(matches[3] | 1 << 8).toString(16).slice(1);
return hex;
}else{
return orig;
}
}
@RadGH
Copy link
Author

RadGH commented May 18, 2022

Test usage (including the above function):

var colors = [];

// Test inputs:
colors.push( "rgb\( 128, 255, 100 \);" );
colors.push( "rgb\( 200, 30, 5 \);" );
colors.push( "rgba\( 128, 255, 100, 0.25 \);" );
colors.push( "rgba\( 200, 30, 5, 0.5 \);" );
colors.push( "rgb\(128,255,100\);" );
colors.push( "rgb\(200, 30,5 \);" );
colors.push( "rgba\(128, 255, 100, 0.25\);" );
colors.push( "rgba\( 200,30,5, 0.5 \);" );
colors.push( "#ffcc00" );
colors.push( "#fc0" );
colors.push( "rgba\( 125 12 5 / 0.5 \);" );
colors.push( "rgba\(125 12 5/0.5\);" );
colors.push( "      rgb\( 128, 255, 100 \)" );
colors.push( "		rgb\( 200, 30, 5 \)" );
colors.push( "	 	rgba\(128, 255, 100, 0.25\)" );
colors.push( "  	  rgba\( 200,30,5, 0.5 \)" );
colors.push( "	 #ffcc00" );
colors.push( " 	#fc0" );
colors.push( "    rgba\( 125 12 5 / 0.5 \)                " );
colors.push( "			rgba\(125 12 5 / 0.5\)	 	" );


let new_colors = [];
for ( var i in colors ) {
	let color = colors[i];
	let hex = rgb_any_to_hex( color );
	new_colors.push({'old': color, 'new': hex});
}

console.table( new_colors );

Output:

image

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