Javascript random alphanumeric string of length n
- Authors
- Name
- Hamza Rahman
- Published on
- -2 mins read-
Here is an example helper function to create a random alphanumeric string of a certain length in javascript.
const randomAlphaNumeric = (length, uppercase = false) => { let alphaNum = '' for ( ; alphaNum.length < length; alphaNum += Math.random() .toString(36) .slice(2) ); alphaNum = alphaNum.slice(0, length)
if (uppercase) { return alphaNum.toUpperCase() } return alphaNum}Here the first parameter allows us to create alphanumeric strings with different lengths and the second parameter lets us select whether to output the result in uppercase or not, by default we keep it lowercase if not provided.
Example usage:
console.log(randomAlphaNumeric(5))console.log(randomAlphaNumeric(10))console.log(randomAlphaNumeric(15))console.log(randomAlphaNumeric(5, true))console.log(randomAlphaNumeric(10, true))Example OutPut:
syw64tc0y8485xsduj90pudav6ywfw3V2SEMMN6UAHZKDA more secure version
Math.random() is fine for non-sensitive values like a UI key or a temporary label. It is not safe for anything security related, such as tokens or passwords, because the output is predictable. For those, use the crypto module, which is available in modern browsers and in Node.js.
const secureAlphaNumeric = (length) => { const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' const values = crypto.getRandomValues(new Uint8Array(length)) return Array.from(values, (v) => chars[v % chars.length]).join('')}
console.log(secureAlphaNumeric(16))If you just need a random unique id and do not care about the exact character set, crypto.randomUUID() is the shortest option of all.
If instead you want to validate a string rather than generate one, see how to check if a string is alphanumeric in JavaScript.
Related articles
Check if a string is alphanumeric in JavaScript
How to check if a string is alphanumeric in JavaScript using a regular expression, including a reusable helper and notes on empty strings and Unicode.
Force an LLM to return JSON in JavaScript
Reliably get JSON from an LLM in JavaScript with OpenAI structured outputs and a Zod schema, instead of prompting for JSON and parsing fragile model text yourself.
The nullish coalescing operator (??) in JavaScript
What the double question mark (??) means in JavaScript: the nullish coalescing operator, how it differs from ||, and the ??= assignment shorthand.

