Skip to content
colors

normalizeHex

The `normalizeHex` function standardizes a HEX color string into a full 6-digit lowercase format. It ensures consistent formatting and validation before further processing.

1 min read118 words

Function Signature

js

normalizeHex(str: string): string

Parameters

  • str (string): The HEX color string to normalize. It may be provided in shorthand (e.g., #abc) or full form (e.g., #aabbcc). It may also omit the leading #.

Return Value

Returns a normalized HEX string in lowercase, always in 7-character format (#rrggbb).

js

normalizeHex("abc");      // "#aabbcc"
normalizeHex("#ABC");     // "#aabbcc"
normalizeHex("#aabbcc");  // "#aabbcc"
normalizeHex("AABBCC");   // "#aabbcc"

Examples

js

// Shorthand HEX expanded
normalizeHex("#f60");
// "#ff6600"

// Full HEX remains unchanged (but lowercased)
normalizeHex("#FF6600");
// "#ff6600"

// Missing # is automatically prefixed
normalizeHex("00aaff");
// "#00aaff"

Error Handling

If the provided string does not match a valid 3-digit or 6-digit HEX pattern, the function throws an error:

js

normalizeHex("#12");
// Error: Invalid hex color

normalizeHex("#12345g");
// Error: Invalid hex color

Usage Notes

  • Always returns lowercase HEX values for consistency.
  • Useful as a preprocessing step before color conversion functions.
  • Supports both shorthand (#abc) and full (#aabbcc) HEX notations.

Previous

parseColor

Next

isValidHex


Top tools

BoardlyLinksyChromoCodeHub

ReadyTools

CareersContactTools
Pricing7 days free
GuidesDocsBlogUpdatesLaraVault

Select Language

Set theme

© 2026 ReadyTools. All rights reserved.