How to Generate a Random String in JavaScript

08/02/2021

Contents

In this article, you will learn how to generate a random string in JavaScript.

Generating a random string in JavaScript

In many applications, you may need to generate random strings for various purposes, such as generating passwords, session IDs, or user names. In JavaScript, you can easily generate random strings using built-in functions.

Using the Math.random() method

The Math.random() method generates a random number between 0 and 1. Here is an example code snippet:

function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}
console.log(generateRandomString(8)); // Output: "JHbX9tRz"

Explanation

  • The generateRandomString() function takes a length parameter that determines the length of the random string to be generated.
  • The characters variable contains all the possible characters that can be used to generate the random string.
  • The for loop generates a random character from the characters string and appends it to the result string.

Using the crypto.getRandomValues() method

The crypto.getRandomValues() method generates cryptographically secure random numbers. Here is an example code snippet:

function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  const randomValues = new Uint32Array(length);
  window.crypto.getRandomValues(randomValues);
  for (let i = 0; i < length; i++) {
    result += characters.charAt(randomValues[i] % charactersLength);
  }
  return result;
}
console.log(generateRandomString(8)); // Output: "wRf0sT69"

Explanation

  • The generateRandomString() function takes a length parameter that determines the length of the random string to be generated.
  • The characters variable contains all the possible characters that can be used to generate the random string.
  • The crypto.getRandomValues() method generates a cryptographically secure random number array.
  • The for loop generates a random character from the characters string and appends it to the result string.