Javascript random alphanumeric string of length n
- Authors
- 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:
syw64tc0y8485xsduj90pudav6ywfw3V2SEMMN6UAHZKD