Matthew C.
—You want to generate a random string of characters in JavaScript. There are many use cases for this, including:
How do you generate a random string or characters?
If the random string does not need to be cryptographically secure, you can use the following function:
function createRandomString(length) { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let result = ""; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } return result; }
This function takes in the length of the random string that you want as an argument and then creates a string output where each character is randomly chosen from the chars
variable. In this case, the possible characters in the random string are alphanumeric. Random characters are chosen using Math.random()
. You can generate variable-length random strings by varying the length of the argument length
using Math.random()
.
It’s important to note that the random number generated is a pseudo-random number. The algorithm used to generate the random number is deterministic. If someone figures out the starting state of the generator algorithm, that has been done for Math.random()
, all future numbers can be predicted. If you need cryptographically secure numbers, use the crypto.getRandomValues()
method.
We can alter the above function to generate cryptographically secure random numbers as follows:
function createRandomString(length) { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let result = ""; const randomArray = new Uint8Array(length); crypto.getRandomValues(randomArray); randomArray.forEach((number) => { result += chars[number % chars.length]; }); return result; }
The Uint8Array
constructor creates a new Uint8Array
array, which represents an array of 8-bit unsigned integers. The crypto.getRandomValues
method populates the Uint8Array
array with random numbers with a value between 0 and 255. We then loop through this array to create a random string. Each character of the random string uses the random number in the randomArray
and the modulo operator to select one of the allowed characters in the chars
string.
The crypto.getRandomValues
method uses a pseudo-random number generator algorithm like Math.random()
. The generated random number is made cryptographically secure by providing the algorithm with a random initial seed value. The random seed value is obtained from an external source of pseudo-random numbers, such as a platform-specific random number function, hardware events such as mouse movements or key presses, or system events such as disk activity or CPU usage.
If you need to generate unique random string characters you can create a UUID (Universally Unique IDentifier). This is a 36-character string usually represented as five hexadecimal strings separated by hyphens. It’s often used as a unique identifier of a record in a database. You can create a UUID in a browser using the crypto web API that’s accessed through the global crypto
property:
const uuid = crypto.randomUUID(); console.log(uuid); // '398de222-5bf9-4754-8e3e-011a55307014'
In Node, you can use the randomUuid()
method of the Node crypto
module.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.