← Download MyJS

MyJS block

randomString 1.0.0

Makes a random string from a set of characters.

Download with this
Exports
randomString
Works in
Browser and Node.js
Requires
random 1.x
Tags
random
The code of version 1.0.0
/**
 * Makes a random string from a set of characters.
 * @param {number} length
 *    How many characters the string should have.
 * @param {string} [chars]
 *    The characters to use, each as likely as the others. Defaults to the
 *    letters A–Z and a–z and the digits 0–9. Emoji and other characters made
 *    of two UTF-16 code units count as one character.
 * @param {boolean} [useCrypto=false]
 *    If `true`, uses `crypto.getRandomValues()` instead of `Math.random()`.
 *    Use it for anything that must not be guessed, like passwords, tokens
 *    and invite codes.
 * @returns {string}
 * @throws {RangeError}
 *    If `length` isn't a whole number of 0 or more, or `chars` is empty.
 *
 * @example <caption>A short ID</caption>
 * randomString(8);
 * // → something like 'q7Rk2mZa'
 *
 * @example <caption>A PIN</caption>
 * randomString(4, '0123456789');
 * // → something like '0472'
 *
 * @example <caption>A token that can't be predicted</caption>
 * randomString(32, undefined, true);
 * // → 32 letters and digits from crypto.getRandomValues()
 */
function randomString(length, chars, useCrypto) {
  const pool = Array.from(chars ?? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
  if (!Number.isInteger(length) || length < 0) {
    throw new RangeError('length must be a whole number of 0 or more.');
  }
  if (!pool.length) {
    throw new RangeError('chars must have at least one character.');
  }
  let result = '';
  for (let i = 0; i < length; i++) {
    result += pool[random(0, pool.length, { useCrypto, returnInt: true })];
  }
  return result;
}

Versions

  1. 1.0.0 Oct 23, 2026

    Initial

JSDoc