How to Generate a Random String in JavaScript

For one reason or another, you might be wondering how to generate a random string in JavaScript.
Thankfully, there are many different ways to approach this problem.
In this post, we will be looking at how to generate a random string with binary characters, hexadecimal characters, and then one where you can specify the characters you want to use.
Generating a random string with binary characters
In all of the examples, we will take advantage of the Math.random()
function. This function returns a random number between 0 and 1.
From there, we can convert it to a string:
const randomNumber = Math.random().toString(2);
console.log(randomNumber);
0.1101011011110101010110110001101111110110100100110001
Now we can use the substr()
method to skip the first two characters and cut off the number at a length of 8
:
const randomNumber = Math.random().toString(2);
const randomString = randomNumber.substr(2, 8);
console.log(randomString);
00001101
Here is a re-usable function:
const generateRandomBinary = (length) => {
const randomNumber = Math.random().toString(2);
return randomNumber.substr(2, length);
};
0110
Generating a random string with hexadecimal characters
For this, we will reuse the previous code, except change the radix of the toString()
method.
This will return a hexadecimal number instead of a binary one:
const randomNumber = Math.random().toString(16);
const randomString = randomNumber.substr(2, 8);
console.log(randomString);
69ee0964
Here is a re-usable function:
const generateRandomHex = (length) => {
const randomNumber = Math.random().toString(16);
return randomNumber.substr(2, length);
};
c142
Generating a random string with a custom character set
For this, we will need to use a different implementation.
First, let's define the set of characters we want to use:
const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
Now let's select from the set a random character:
const randomCharacter = characters[Math.floor(Math.random() * characters.length)];
Now, let's make a method that takes in a length and returns a random string of that length:
const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
const generateRandomString = (length) => {
let randomString = "";
for (let i = 0; i < length; i++) {
randomString += characters[Math.floor(Math.random() * characters.length)];
}
return randomString;
};
console.log(generateRandomString(8));
6vudynt3
Conclusion
In this post, we took a look at how to randomly generate binary, hexadecimal, and custom strings.
From here, you can use for anything ranging from hashing to generating seeds.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!