javascript

Create random string in Javascript

In this article, we will show you how to create a random string in Javascript. A random string is a string of random characters.

Create random string in Javascript

In order to create a random string in Javascript:

  1. Generate random numbers using Math.random() function .
  2. Convert the above number to a string using toString(36) and get a random string using substring (2, 15) function.

Example 1: Using Math.random()

We will be using Math.random()toString() and substring() functions to generate a random string here.

const result = Math.random().toString(36).substring(2, 15);

console.log(result);

Live Demo

The code defines a constant named "result"

The value assigned to the result is the result of calling the Math.random() function, which returns a random number between 0 and 1, and then calling the toString() function on that number, which converts it to a string. The toString() function takes an optional argument that specifies the base to use for representing numeric values. In this case, the base is 36, which means that the string will contain letters and numbers.

The final part of the string (after the "2,") is the number of characters that should be in the string. In this case, the string will be 15 characters long.

The result is then logged into the console.


Example 2: Generate a random String using For loop in Javascript

Here, we will learn how to generate a random string using a for loop in JavaScript.

function makeString(strLen) {
    var result = '';
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var cLength = chars.length;
    for (var i = 0; i < strLen; i++) {
        result += chars.charAt(Math.floor(Math.random() * cLength));
    }
    return result;
}

console.log(makeString(10));

Live Demo

The function makeString() takes in a parameter strLen. It creates a variable called result and sets it equal to an empty string. 

It also creates a variable called chars which contains all the uppercase and lowercase letters of the alphabet, as well as all the numbers.

The variable cLength is set equal to the length of the chars variable. There is a for loop that runs for as long as i is less than strLen. Inside the for loop, the result is set equal to itself plus a random character from the chars string.

The function then returns the result string. Finally, the makeString() function is called with a parameter of 10, and the resulting string is logged to the console.

Was this helpful?