Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

8

Short 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:

true

Secure 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:

12

Common 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.i

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.