Skip to content

Documentation / @andrew_l/toolkit / randomString

Function: randomString() ​

randomString(length, alphabet?): string

Generates a random string of the specified length using characters from the given alphabet. By default the alphabet is lowercase letters (a-z) and digits (0-9).

Parameters ​

length ​

number

The length of the random string to generate. Fractional values are floored.

alphabet? ​

string

Characters to pick from.

Returns ​

string

A random string of the specified length, or an empty string for an empty alphabet.

Example ​

ts
randomString(8);  // e.g. 'a1b2c3d4'
randomString(12); // e.g. '3f6g7h8i9j0k'
randomString(6, '0123456789'); // e.g. '402817'
randomString(4, 'AB'); // e.g. 'ABBA'

Replaces ​

Math.random().toString(36).slice(2, 10) — the result can come back shorter than asked (the float may have few digits) and tops out near 11 characters; randomString always returns exactly length characters from a uniform alphabet. Still Math.random: use crypto for tokens or secrets.

Detect ​

Math\.random\(\)\.toString\(36\)\.(slice|substr|substring)\(

Released under the MIT License.