Generate a random string from given characters
Draw characters from an alphabet with a cryptographic generator, without bias.
function randomString(length, alphabet) {
if (alphabet.length < 2 || alphabet.length > 256) throw new RangeError('alphabet must have 2 to 256 characters');
const limit = 256 - (256 % alphabet.length);
let result = '';
while (result.length < length) {
for (const byte of crypto.getRandomValues(new Uint8Array(length))) {
if (byte < limit && result.length < length) result += alphabet[byte % alphabet.length];
}
}
return result;
}
Usage
const code = randomString(8, '0123456789');
/^[0-9]{8}$/.test(code); // → true
randomString(24, 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'); // e.g. 'Q7MZ3H8KJ2WNC5RTV9XPLD4A'
Know the limits
- Uses crypto.getRandomValues, a global in browsers and Node.js 19+. The original used Math.random, which is predictable and unsuitable for tokens.
- Rejection sampling: bytes at or above limit are discarded, so every character is equally likely. byte % length alone would favour the first characters.
- Characters must be single UTF-16 units, such as ASCII; 2 to 256 of them.
- Strength is length × log2(alphabet size) bits: 22 characters from 62 give about 131 bits.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Generate a random string from given characters from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses crypto.getRandomValues with rejection sampling instead of Math.random. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.