Function Signature
js
normalizeHex(str: string): stringParameters
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 colorUsage 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.