When developing web projects (either front-end or back-end), random strings are commonly used for various purposes, such as making unique identifiers for user accounts or objects in a database or creating random file names to avoid naming conflicts. This practical, example-based article will walk you through a couple of different ways to generate a random string in JavaScript.
Using Math.random() and charAt()
We can use the Math.random() function (that is available on both the browser environment and Node.js environment by default) to generate a random string of the specified length. It helps us randomly select characters from the character’s string (that includes all letters and numbers) by using the charAt() function.
Example:
const generateRandomString = (length) => {
let result = '';
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
console.log(generateRandomString(5));
console.log(generateRandomString(30));
The output (that will change each time you execute the code):
G4vcg
script.js:13 md2pNVDvOspbyycygm8B0g4kjYqv0e
Using window.crypto.getRandomValues()
This approach is quite similar to the previous one, but there is a key differentiating point is that we will use the window.crypto.getRandomValues() function instead of the Math.random() function.
Example:
const generateRandomString = (length) => {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let result = '';
// Create an array of 32-bit unsigned integers
const randomValues = new Uint32Array(length);
// Generate random values
window.crypto.getRandomValues(randomValues);
randomValues.forEach((value) => {
result += characters.charAt(value % charactersLength);
});
return result;
}
console.log(generateRandomString(10));
console.log(generateRandomString(25));
Output:
jLogAh04m8
script.js:15 CcJRRcojGbsVWETXBVG5rBpch
Using Math.floor(Math.random() * Date.now())
We can create a random string by multiplying a random number with the current timestamp and then converting it to a base-36 string using the toString() function.
Example:
const generateRandomString = () => {
return Math.floor(Math.random() * Date.now()).toString(36);
};
console.log(generateRandomString());
Output:
goq2iade
This approach is quick and simple, but we cannot control the length of the output.
Using a third-party package
There is a plethora of open-source packages that provide functionalities to help you produce random strings. One of the most popular is uuid.
You can install it to your project by running the following command:
npm i uuid
Then use it like so:
import { v4 as uuidv4 } from 'uuid';
const randomString1 = uuidv4();
const randomString2 = uuidv4();
console.log(randomString1);
console.log(randomString2);
Output:
b8d03ea8-db49-4afb-8b09-5727b1ea4b10
76adaeb0-5129-4c84-9984-ccd7b0f0927b
The v4 function generates a random version 4 UUID (UUID stands for Universally Unique Identifier).