Skip to content

Function random

Source: Random.ts

Generates a random string of the specified length by sampling characters from a charset string. The function uses Math.random() for sampling, so it is not cryptographically secure.

Import

ts
import { random, ERandomStringCharset, DEFAULT_RANDOM_CHARSET } from '@litert/utils-string';

Signature

ts
function random(length: number, charset?: string): string;

Parameters

  • Parameter length: number

    The desired length of the output string. If <= 0, an empty string is returned.

  • Parameter charset?: string (default: DEFAULT_RANDOM_CHARSET)

    The pool of characters to sample from. All characters in the string must be unique for uniform distribution.

Return Value

A random string of the requested length.

Examples

ts
import { random, ERandomStringCharset } from '@litert/utils-string';

// Default charset: A-Z, a-z, 0-9
random(16);  // e.g. 'aB3xZ9mK2qTyWpLe'

// Only digits
random(6, ERandomStringCharset.DEC_DIGIT); // e.g. '847302'

// Lowercase hex
random(8, ERandomStringCharset.LOWER_HEX_DIGIT); // e.g. 'a3f09c12'

// Custom charset
random(5, 'abc');  // e.g. 'bcaac'

// Length 0
random(0);  // ''