Skip to main content

Generate a Random ID

generateRandomID

The generateRandomID function creates a customizable random alphanumeric ID with options for a prefix, suffix, timestamp, case formatting, and a separator.

Function Signature

const generateRandomID = (options?: RandomIdOptions) => string;

Parameters

  • options (optional): Configuration options for generating the random ID.

Options

OptionTypeDefaultDescription
prefixstring''A string to prepend to the ID.
suffixstring''A string to append to the ID.
timeStampbooleanfalseWhether to include the current timestamp.
lengthnumber16Length of the random alphanumeric string.
separatorstring''The separator between parts of the ID.
caseOption'upper' | 'lower' | nullnullConverts the ID to uppercase, lowercase, or keeps default case.

Return Value

Returns a random alphanumeric ID string, optionally formatted with a prefix, suffix, timestamp, separator, and case transformation.


Example Usage

Default ID Generation

Import

import { generateRandomID } from 'nhb-toolbox';
generateRandomID();
// Output: 'g7sk49h32mzxp1qv'

ID with Prefix, Suffix, and Timestamp

generateRandomID({
prefix: 'user',
suffix: 'end',
timeStamp: true,
separator: '-'
});
// Output: 'user-1709056123456-a1b2c3d4e5f6g7h8-end'

Uppercase ID with Custom Length

generateRandomID({ length: 8, caseOption: 'upper' });
// Output: 'A1B2C3D4'