function randchar
randchar(
n?: number,
strset?: string,
): string

Generates a random alphanumeric string.

Generates a random string of specified length using the provided character set. If no character set is provided, the default set includes uppercase and lowercase letters and digits.

Examples

Generate a random string of 12 characters from a custom set

import { assertEquals } from "jsr:@std/assert";

const result1 = randchar(12, 'ABCD!-|/%&$1234567890');
assertEquals(result1.length, 12);
assertEquals(result1.split('').every(char => 'ABCD!-|/%&$1234567890'.includes(char)), true);

Generate a random string of 16 characters from a different custom set

import { assertEquals } from "jsr:@std/assert";

const result2 = randchar(16, 'ABCDEFGHILMNOPQRSTUVZ-1234567890');
assertEquals(result2.length, 16);
assertEquals(result2.split('').every(char => 'ABCDEFGHILMNOPQRSTUVZ-1234567890'.includes(char)), true);

Generate a random string of 8 characters using the default set

import { assertEquals } from "jsr:@std/assert";

const result3 = randchar(8);
assertEquals(result3.length, 8);

Parameters

optional
n: number = 6

The number of characters to generate. Defaults to 6 if not provided.

optional
strset: string = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

The character set to use for generating the random string.

Return Type

string

A randomly generated string of length n.