How to generate a random string
Short answer
Pick random characters from a set in a loop:
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < 8; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
console.log(result.length);Output:
8Short and quick
For a non-secret id, a number in base 36 is enough: these are digits and Latin letters:
const id = Math.random().toString(36).slice(2, 10);
console.log(/^[a-z0-9]+$/.test(id));Output:
trueSecure codes and tokens
Math.random() is predictable. For passwords, tokens and confirmation codes, use crypto.getRandomValues():
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const bytes = crypto.getRandomValues(new Uint8Array(12));
const token = [...bytes].map((byte) => chars[byte % chars.length]).join('');
console.log(token.length);Output:
12Common mistake
Math.random().toString(36) sometimes gives fewer characters than expected, so do not rely on its exact length:
console.log((0.5).toString(36));Output:
0.iFunctions used in this recipe
- Math.random — Returns a random number between 0 and 1.
- crypto.randomUUID — Creates a random unique identifier (UUID).
- String.prototype.slice — Returns part of a string.