To generate a random string in JS you should start by defining the set of characters that will be used to generate that random string. Let’s go!
So, let’s start by defining a string that holds all lowercase letters and 10 digits.
const charset = 'abcdefghijklmnopqrstuvwxyz0123456789';
The second step is to get a random symbol from the charset
string.
I’ll use Math.random
for it.
Math.random
return a random value between 0 and 1, so I multiply it by the charset length
and then use Math.floor
to convert it to the integer.
const randomChar = charset.charAt(Math.floor(Math.random() * charset.length));
The final step is to generate however many random characters we need and compile them into a string.
Let’s create a function for it.
const generateRandomString = (length = 8, charset = 'abcdefghijklmnopqrstuvwxyz0123456789') => {
const result = [];
for(let i = 0; i < length; i++) {
result.push(charset.charAt(Math.floor(Math.random() * charset.length)));
}
return result.join('');
}
You can use the function generateRandomString
by passing in the number of characters that you’d like to
get in the result string as well as the character set.
I’ve added default values for charset
and length
to make the function generateRandomString
usable
without any arguments.
console.log(generateRandomString());
console.log(generateRandomString());
console.log(generateRandomString());
As a result I got 3 random strings of length 8.
w1np7gbv
mj3szuyt
hh2pj0xx
I can also change the charset to be only digits and thus get the numerical string.
console.log(generateRandomString(8, '0123456789'));
console.log(generateRandomString(12, '0123456789'));
console.log(generateRandomString(16, '0123456789'));
Here are 3 random numerical strings of lengths 8, 12 and 16 characters.
27490427
205470247095
5475917413655249