Hex-to-RGB Conversion

JavaScript FAQ | JavaScript Colors FAQ  

Question: How do I convert a hex color string (e.g. "FFFFCC") to numeric RGB values?

Answer: Try this script for hex-to-RGB color conversion:   [Looking for RGB-to-Hex?]

     R: G: B:  

The JavaScript source code is simple:

R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
The script uses a helper function cutHex() to check if the # character is present in the beginning of the input hexadecimal value. If so, the cutHex() function cuts off the # so that only the hexadecimal digits are left in the input value. We use the standard JavaScript method substring() to get the R, G, B (red, green, blue) hex substrings from the input hexadecimal value. Finally, the script parses the R, G, B values from hexadecimal string to number using the standard function parseInt(string,16); the second argument 16 specifies that the string must be parsed as a hexadecimal (base-16) value.

See also:
JavaScript Colors FAQ
RGB to Hex color converter
Hex to CMYK color converter
RGB to CMYK color converter  
RGB to HSV color converter
Changing the page background color
Changing the color of HTML elements
Predefined color names (alphabetical list)
Applying another stylesheet to my page
Changing the mouse cursor style

Copyright © 1999-2012, JavaScripter.net.