Generate a random string with given length
Return a lowercase Base32 identifier from a cryptographic generator.
function randomId(length) {
const alphabet = '0123456789abcdefghjkmnpqrstvwxyz';
return Array.from(crypto.getRandomValues(new Uint8Array(length)), byte => alphabet[byte % 32]).join('');
}
Usage
const id = randomId(12);
id.length; // → 12
/^[0-9a-hjkmnp-tv-z]+$/.test(id); // → true
randomId(12); // e.g. 'k3x9m2q7v0ad'
Know the limits
- 32 symbols (Crockford’s Base32, lowercase) divide 256 evenly, so every symbol is equally likely without rejection sampling. It omits i, l, o and u, which are easy to misread.
- The original took one base-36 digit from Math.random().toString(36): predictable, and empty for some values such as 0.
- Each character carries 5 bits: 26 characters give 130 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 with given length from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses crypto.getRandomValues and an unbiased 32-symbol alphabet; the original used Math.random and could return empty characters. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/generate-a-random-string-with-given-length.mdx in akamind/1loc, commit 0a77f131b22d. 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.