JavaScript

Random String Generator Using JavaScript

In JavaScript, you can easily create a random string generator with the help of the Math random() method. There are two approaches to creating a random string generator with Math random, one uses this method in combination with Math floor, and the other uses this with the toString() method. This article will focus on both of these methods one by one.

Method 1: Creating a Random String Generator Using the Math Floor() and Math random()

To start, first, create a string variable with all the possible characters your randomly generated string can have. For example, if you want to create a random string with the character’s possibilities being “a-z”, “A-Z”, “0-9” and a few special characters like “[email protected]#$%^&*”. To do this, use the following line:

string =
  "[email protected]#$%^&*";

After that, you want to get the length of this string variable by using the length property:

length = string.length;

After that, create an empty string variable which is going to store our randomly generated string:

var resultString = "";

And then create a for loop, and the number of iterations of the for loop are going to define the number of characters the randomly generated string is going to have. For now, let’s set the number of iterations to 5 with the following lines:

for (i = 1; i<=5; i++) {
    // Next lines are going to come in here
}

Inside this for loop, you are going to select a character from our characters to string randomly and then append that character onto the resultString variable with the following line:

resultString += string.charAt(Math.floor(Math.random() * length));

Let’s break this line down and see what is actually happening in here:

  • Math random() is used to generate a random floating point value between 0 and 1
  • The result from Math Random is multiplied by the length variable in which we have the total number of possibilities for each character
  • After that multiplication, it is still a floating-point value. Therefore, we are rounding the number down to an integer value
  • We are using this integer value as the index value from our string which contains all the possible characters
  • Lastly, we are simply appending the character fetched at that particular index to our resultString

Afterwards, come out of the for loop and simply pass the resultString to the console log function to print the result on the terminal:

console.log(resultString);

The complete code snippet is as:

string =
  "[email protected]#$%^&*";

length = string.length;
var resultString = "";
for (i = 1; i <= 5; i++) {
  resultString += string.charAt(Math.floor(Math.random() * length));
}
console.log(resultString);

Upon multiple execution this code produces the following outcome on the terminal:

As you can see, for every execution we are generating a new random string of length 5.

Method 2: Generating Random Strings With the Math random() and the toString() Method

This time around, we are going to be using the argument inside the toString() method to define the base of the string to be parsed. This might seem confusing but it’s all going to go away with an example. Start of by creating a result string like this:

const resultString = Math.random().toString(36).substring(2, 7);

Now, let’s explore this statement part by part:

  • Math random() creates a random floating point number between 0 and 1
  • After that, we convert that number into string using toString() method and set the base as 36
  • Values greater than 10 would be given Alphabetic values just like the working of a hexadecimal number system.
  • After that, we are only picking a substring from index value 2 to 7

After that, we can simply pass the resultString in the console log function to print it onto the terminal:

console.log(resultString);

Execute the program a couple of times and observe the output to be following:

As you can observe in the output, we were able to generate a random string with a length of 5.

However, method 1 is a little longer but it is much better because it allows you to define the possibility of the characters that can be placed in the string which is far greater than the 26 lower case alphabets and the 10 numbers that we get with method 2.

Conclusion

A random string generator can easily be created in JavaScript in two different manners. Both of these methods essentially use the Math random() as its core, but the difference comes with one using the Math floor() method and the other using the toString() method. This article has shown both of the methods along with their examples to generate random strings with the length set to 5.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.