Generate random string in Javascript
Okay, hear me out. I saw people posting code snippets on how to generate random strings in Javascript. So here is mine.
Is my code the best? No.
Is my code the fastest? Nope.
Is it going to change the world? LoL, no.
Generate random string #
const generateRandomString = (n: number = 15): string => {
// generate a random string
let result = "";
for (let i = 0; i < n; i++) {
const randomNumber =
Math.random() > 0.5
? Math.floor(65 + Math.random() * 25)
: Math.floor(97 + Math.random() * 25);
// convert the random number to a character (ASCII value)
const randomChar = String.fromCharCode(randomNumber);
// append the random character to the result string
result += randomChar;
}
return result;
};
Generate random alphanumeric string #
const generateRandomAlphaNumericString = (n: number = 15): string => {
// generate a random alphanumeric string
let result = "";
for (let i = 0; i < n; i++) {
const randomNumber =
Math.random() > 0.5
? Math.floor(65 + Math.random() * 25)
: Math.random() > 0.5
? Math.floor(48 + Math.random() * 9)
: Math.floor(97 + Math.random() * 25);
// convert the random number to a character (ASCII value)
const randomChar = String.fromCharCode(randomNumber);
// append the random character to the result string
result += randomChar;
}
return result;
};
Conclusion #
That's it. Next time, instead of installing and importing a package to generate a random string, consider using the above snippets as a good starting point.
It's probably a good "truly random string" solution.
Thank you for reading.