Skip to content

normalizeHexString

Guarantees a normalized hexadecimal string or returns null.

This helper validates that a value is a byte-aligned hexadecimal string and normalizes it to lowercase. It performs no coercion beyond trimming whitespace and lowercasing valid hexadecimal characters.

Use this helper when you need predictable, canonical hex data before validation, decoding, hashing, or storage.

Signature

function normalizeHexString(value: unknown): string | null

Parameters

Name Data type Description
value unknown The value to normalize.

Returns

One of:

  • A lowercase hexadecimal string.
  • null if the value is not a valid hex string.

Behavior

  • Accepts strings containing only:
  • 0–9.
  • a–f.
  • A–F.
  • Trims surrounding whitespace.
  • Normalizes all hex characters to lowercase.
  • Requires an even-length string.
  • Rejects:
  • Empty strings.
  • Odd-length strings.
  • Non-hex characters.
  • Non-string values.
  • Never throws and never mutates input.

Examples

normalizeHexString("deadbeef")
// "deadbeef"

normalizeHexString("DEADBEEF")
// "deadbeef"

normalizeHexString("  AaBbCcDd  ")
// "aabbccdd"

normalizeHexString("abc")
// null

normalizeHexString("0x12")
// null

normalizeHexString(123)
// null

Notes

This helper does not:

  • Accept 0x or # prefixes.
  • Pad odd-length strings.
  • Interpret hex numerically.
  • Even length is required to ensure byte alignment.
  • Behavior is deterministic and allocation-safe.