Generate a random string from given characters

Draw characters from an alphabet with a cryptographic generator, without bias.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

generate-a-random-string-from-given-characters.js
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

usage.js
const code = randomString(8, '0123456789');
/^[0-9]{8}$/.test(code); // → true
randomString(24, 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'); // e.g. 'Q7MZ3H8KJ2WNC5RTV9XPLD4A'

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.