Skip to content
colors

hexToRgb

The `hexToRgb` function converts a HEX color string into an RGB object. It supports both 3-digit and 6-digit HEX formats and outputs the red, green, and blue components as integers between 0 and 255.

1 min read151 words

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).

Previous

isValidHex

Next

rgbToHex


Top-Werkzeuge

BoardlyLinksyChromoCodeHub

ReadyTools

KarriereKontaktWerkzeuge
Preise7 Tage gratis
AnleitungenDocsBlogUpdatesLaraVault

Sprache wählen

Thema wählen

© 2026 ReadyTools. Alle Rechte vorbehalten.