Generate random string in Javascript

Ramit
1 min readApr 22, 2024

Wanna know how to generate random strings in Javascript without importing any packages or dependencies?

Even better, it can be used with Deno or Bun without any modifications.

Are you ready?

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;
};
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;
};

For more informative posts, look here https://blog.ramit.io/. Thanks.

--

--

Ramit

Data Science & deep learning entusiast. Polyglot developer. Introvert. Minimalist.