← Back to utilities
crypto

random-string

Generates a random string of specified length. Creates a cryptographically secure random string using the specified character set. By default uses alphanumeric characters (a-z, A-Z, 0-9). Useful for generating tokens, IDs, or passwords.

Installation

npx fragmen add crypto/random-string

Source Code

/**
 * Generates a random string of specified length.
 *
 * Creates a cryptographically secure random string using the specified
 * character set. By default uses alphanumeric characters (a-z, A-Z, 0-9).
 * Useful for generating tokens, IDs, or passwords.
 *
 * @tags crypto, string-manipulation
 * @param {number} length The desired length of the random string
 * @param {string} charset Optional custom character set to use (defaults to alphanumeric)
 * @returns {string} A random string of the specified length
 *
 * @example
 * ```typescript
 * // Generate a 16-character alphanumeric string
 * const token = randomString(16);
 * // 'aB3cD5eF7gH9iJ2k'
 *
 * // Generate a numeric PIN
 * const pin = randomString(6, '0123456789');
 * // '847235'
 *
 * // Generate a custom character set
 * const code = randomString(8, 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789');
 * // 'A3K9MN2X' (excludes confusing characters like 0, O, I, 1)
 *
 * // Empty string if length is 0 or negative
 * randomString(0); // ''
 * randomString(-5); // ''
 * ```
 */
export function randomString(
  length: number,
  charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
): string {
  if (length <= 0 || !Number.isInteger(length)) {
    return '';
  }

  if (!charset || charset.length === 0) {
    throw new Error('Charset must be a non-empty string');
  }

  let result = '';

  // Use crypto.getRandomValues if available for better security
  if (
    typeof crypto !== 'undefined' &&
    'getRandomValues' in crypto &&
    typeof (crypto as Crypto).getRandomValues === 'function'
  ) {
    const randomValues = new Uint8Array(length);
    (crypto as Crypto).getRandomValues(randomValues);

    for (let i = 0; i < length; i++) {
      result += charset[randomValues[i] % charset.length];
    }
  } else {
    // Fallback to Math.random()
    for (let i = 0; i < length; i++) {
      result += charset[Math.floor(Math.random() * charset.length)];
    }
  }

  return result;
}

Examples

// Generate a 16-character alphanumeric string
const token = randomString(16);
// 'aB3cD5eF7gH9iJ2k'

// Generate a numeric PIN
const pin = randomString(6, '0123456789');
// '847235'

// Generate a custom character set
const code = randomString(8, 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789');
// 'A3K9MN2X' (excludes confusing characters like 0, O, I, 1)

// Empty string if length is 0 or negative
randomString(0); // ''
randomString(-5); // ''

Related Utilities

uuid

crypto

Generates a UUID v4 (Universally Unique Identifier). Creates a random UUID using cryptographically strong random values when available (crypto.randomUUID or crypto.getRandomValues), falling back to Math.random() if needed. Follows RFC 4122 version 4 format.

#crypto#pure

camel-case

string

Converts a string to camelCase. Transforms a string by removing spaces, underscores, and hyphens, then capitalizing the first letter of each word except the first one. Commonly used for JavaScript variable names, object properties, and function names.

#pure#string-manipulation#formatting

capitalize

string

Capitalizes the first letter of a string. Converts the first character to uppercase while leaving the rest unchanged. Safely handles edge cases like empty strings and non-string inputs.

#pure#string-manipulation#formatting

is-email

string

Validates if a string is a valid email address. Uses a practical regex pattern that covers most common email formats while avoiding overly complex RFC-strict validation. Handles international characters in the local part and common TLDs.

#validation#string-manipulation

kebab-case

string

Converts a string to kebab-case. Transforms a string by converting it to lowercase and replacing spaces, underscores, and camelCase boundaries with hyphens. Useful for creating URL slugs, CSS class names, and file names.

#pure#string-manipulation#formatting

pad-end

string

Pads the end of a string with another string until it reaches the target length. If padString is '', the original string is returned (mirrors native behavior).

#pure#string-manipulation#formatting

Quick Actions

Estimated size:1.92 KB

Tags

Parameters

lengthnumber

The desired length of the random string

charsetstring

Optional custom character set to use (defaults to alphanumeric)

Returns

string

A random string of the specified length