Function Signature
js
hexToRgb(hex: string): { r: number, g: number, b: number }Parameters
hex(string): A HEX color string, either in shorthand (#rgb) or full (#rrggbb) format. The leading#may be omitted.
Return Value
An object containing the red (r), green (g), and blue (b) components as integers from 0 to 255.
js
hexToRgb("#ff6600");
// { r: 255, g: 102, b: 0 }
hexToRgb("#0af");
// { r: 0, g: 170, b: 255 }Examples
js
// Convert full HEX
console.log(hexToRgb("#ffffff"));
// { r: 255, g: 255, b: 255 }
// Convert shorthand HEX
console.log(hexToRgb("#f60"));
// { r: 255, g: 102, b: 0 }
// Without leading #
console.log(hexToRgb("00aaff"));
// { r: 0, g: 170, b: 255 }Error Handling
The function assumes a valid HEX input. If the input is malformed (e.g., invalid characters or wrong length), parseInt may yield unexpected results. Use isValidHex or normalizeHex before calling this function to ensure correctness.
Usage Notes
- Supports both shorthand and full HEX notations.
- Does not handle alpha channels. For RGBA, use a different parser or extend functionality.
- Works well as a bridge function for further conversions (e.g., RGB → HSL).