Clue Mediator

Generate a random string in JavaScript

📅May 5, 2022

In this short article, you will learn how to generate a random string in JavaScript. We'll learn how to make strings of arbitrary length by selecting characters at random from A-Z, a-z, and 0-9. There are multiple ways to generate a random string but we will look at two of them.

Checkout more articles on JavaScript

Ways to generate a random string in JavaScript

  1. Generate a random string from characters
  2. Built-in methods to generate a random string

1. Generate a random string from characters

The `Math.random()` function is used in this example to get random characters from the provided characters (A-Z, a-z, 0-9).

// declare the list of characters
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = '';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

generateString(5); // Output: 5DYmV

2. Built-in methods to generate a random string

Now let’s use the built-in methods to generate a random string.

function generateString(length) {
    const result = Math.random().toString(36).substring(2, length + 2)
    return result;
}

generateString(5); // Output: ynbos

The `Math.random()` function provides a random value between `0` and `1`.
The `toString(36)` method, `36` represents base 36. The `toString(36)` represents digits beyond `9` by letters.
The `substring()` method returns number of characters.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂