How to Generate a Random String in JavaScript

Published April 2025 · 4 min read

Method 1: Quick One-Liner

Math.random().toString(36).substring(2, 10);
// Output: "k7x9f2m1"

Method 2: Custom Length & Characters

function randomString(length, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
  return Array.from({length}, () => chars[Math.floor(Math.random() * chars.length)]).join('');
}
randomString(16); // "Kx9fM2nB7pQwR4sT"

Method 3: Crypto-Secure (for tokens/passwords)

function secureRandom(length) {
  const arr = new Uint8Array(length);
  crypto.getRandomValues(arr);
  return Array.from(arr, b => b.toString(16).padStart(2, '0')).join('').slice(0, length);
}
secureRandom(32); // "a7f2c9e1b4d8..."

Method 4: UUID v4

crypto.randomUUID();
// "550e8400-e29b-41d4-a716-446655440000"

Method 5: Node.js

const crypto = require('crypto');
crypto.randomBytes(16).toString('hex');
// "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"

Generate Online

Use our Password Generator or UUID Generator.

Related