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): stringParameters
| Parameter | Type | Description |
|---|---|---|
length | number | Number of hexadecimal characters to generate. |
uppercase | boolean (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
lengthis0or negative, an empty string is returned. - It uses
crypto.getRandomValueswhen available for secure randomness, and falls back toMath.randomif not. - The output is a string of hex characters (
0–9,a–forA–Fwhen uppercase) with no prefixes or separators. - The
uppercaseparameter 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
- randomBytes - Generate random bytes (
Uint8Array) - randomNumeric - Generate random numeric strings
- randomAlphaNumeric - Generate random alphanumeric strings
Last updated: Tue, Jun 16, 2026 06:17:07PM (UTC)
