How to Generate a Random String With JavaScript

Learn about the three best ways to generate a random string with JavaScript, and in which situation to use each.

Published Categorized as JavaScript

Suppose you need to generate a random string with JavaScript. What’s the best way to do that?

That’s the question I found myself asking when I was working on a script for generating a random identifier for a website’s visitors and storing it in a cookie. And since you’re here reading this, you’re probably interested in the same. So let’s no waste time and get straight to the meat of it.

Generating a Random String With JavaScript

Generally, there are three ways to generate a random string with JavaScript:

MethodSideDescriptionUse Case
Math.random() and charAt() methodFrontend / Client-sideGenerates a random string using the JavaScript Math.random() function to select random characters from a predefined set of characters. The characters are concatenated to form the final string.For generating simple, non-cryptographically secure random strings, such as session IDs or unique identifiers. Slow but compatible with legacy browsers.
crypto APIFrontend / Client-sideGenerates a cryptographically secure random string using the crypto.getRandomValues() method, which provides a secure source of random numbers. The numbers are then used to select characters from a predefined set of characters.For generating secure random strings, such as passwords or secret tokens, where the risk of prediction is high. Fast but available only on modern browsers.
uuid/v4 libraryBackend / Server side (Node.js only)Generates a version 4 Universally Unique Identifier (UUID), which is a string that is guaranteed to be unique across time and space. The uuid/v4 library implements the standard for UUIDs, and can be easily integrated into a Node.js project.For generating unique identifiers that need to be universally unique, such as database primary keys or resource IDs. Only for Node.js backends (unless you add a uuid library to your frontend).

Which to use depends on your environment and use case. Nine times out of ten, calling the crypto Web API will be your best solution. Unless you need legacy browser support, in which case you’ll want to use the Math.random() and charAt() method, or you’re building a Node.js backend, where you can use the uuid/v4 library.

With Math.random() and charAt()

This method involves creating an empty string, defining a set of characters for the random string you want to generate, and using the Math.random() static method to generate a random index for each. The character at that index is then retrieved using the charAt() method and appended to the resulting string.

Here’s an example:

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

// Generate a random string 36 characters long
generateRandomString(36);

With the crypto() Web API

The crypto API provides a fast and secure way to generate random values. To use this method, you need to first check if the crypto API is available on the user’s device (or if the msCrypto API is available on older versions of Internet Explorer), which may not be the case on older browsers.

Once you’ve confirmed that the crypto API is there, you can use the getRandomValues() method to generate an array of random values, which can then be used to construct the random string.

Here’s an example:

function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  const crypto = window.crypto || window.msCrypto;
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  array.forEach(x => result += characters[x % charactersLength]);
  return result;
}

// Generate a random string 36 characters long
generateRandomString(36);

With the uuid() Library

Now let’s go over a method that you can use if you’re building a Node.js backend.

The uuid library provides a simple way to generate universally unique identifiers called “UUIDs.” To generate a random string, you can use the uuidv4() function, which returns a string of 36 characters with dashes. This string can be used as a random string or shortened as needed.

Here’s an example:

const uuidv4 = require('uuid/v4');

function generateRandomString() {
  return uuidv4();
}

// Generate a random string 36 characters long
const randomString = generateRandomString();

The uuid library is designed to be used in a Node.js backend environment, where it can be installed as a package using npm and included in your code using the require statement. In the browser, it’s not possible to use the require statement, and you will receive the “Uncaught ReferenceError: require is not defined” error.

However, there are libraries available that provide a similar functionality in the browser, such as the uuid.js library. You can include this library in your HTML code using a <script> tag, then use its methods to generate UUIDs.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *