# Generate a random string from given characters

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

Canonical: https://1loc.dev/random/generate-a-random-string-from-given-characters/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
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

```javascript
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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/generate-a-random-string-from-given-characters.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
