Javascript random alphanumeric string of length n

Authors
  • avatar
    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:

syw64
tc0y8485xs
duj90pudav6ywfw
3V2SE
MMN6UAHZKD

A 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.