Skip to content

Instantly share code, notes, and snippets.

@blakek
Created January 30, 2026 18:43
Show Gist options
  • Select an option

  • Save blakek/3b36dc35d353731753643b0dc64b41d4 to your computer and use it in GitHub Desktop.

Select an option

Save blakek/3b36dc35d353731753643b0dc64b41d4 to your computer and use it in GitHub Desktop.
Create randomized string
const unambiguousCharacters = "0123456789abcdefghjkmnpqrstvwxyz"; // excludes i, l, o, u, and uppercase letters
/** Creates a random string of a specified length and using specified characters. */
export function createRandomString(
length = 16,
characterSet = unambiguousCharacters
): string {
if (length <= 0) {
throw new RangeError("Length must be a positive integer.");
}
if (characterSet.length <= 0) {
throw new RangeError("Character set must not be empty.");
}
// Using a Uint8Array limits us to 256 unique characters (2^8), which is sufficient for most use cases.
if (characterSet.length > 256) {
throw new RangeError(
"Character set must not contain more than 256 characters."
);
}
const randomValues = new Uint8Array(length);
globalThis.crypto.getRandomValues(randomValues);
return Array.from(
randomValues,
(n) => characterSet[n % characterSet.length]
).join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment