Toolbox-XToolbox-X

Generate Random Hex

Generate a random hexadecimal string of the specified length.

randomHex

The randomHex function generates a random hexadecimal string of the specified length.

Info

Does not rely on Node.js or Web APIs. Works on any JS engine

Function Signature

randomHex(length: number, uppercase?: boolean): string

Parameters

ParameterTypeDescription
lengthnumberNumber of hexadecimal characters to generate.
uppercaseboolean (optional)Whether to return uppercase A-F characters. Default: false

Return Value

Returns a randomly generated hexadecimal string of the specified length.

Example Usage

playground.ts

Use Cases

  • Generating unique identifiers
  • Creating random tokens for authentication
  • Generating cryptographic nonces
  • Creating temporary file names

Implementation Notes

  • This function generates a random hexadecimal string of the specified length.
  • If length is 0 or negative, an empty string is returned.
  • It uses crypto.getRandomValues when available for secure randomness, and falls back to Math.random if not.
  • The output is a string of hex characters (0–9, a–f or A–F when uppercase) with no prefixes or separators.
  • The uppercase parameter controls whether the hex characters are uppercase or lowercase. By default, it returns lowercase hex.
  • The function is designed to be efficient and works in both browser and Node.js environments without relying on external libraries.

See Also

Last updated: Tue, Jun 16, 2026 06:17:07PM (UTC)

On this page