Javascript random alphanumeric string of length n

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
1 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