Random Code Generator JavaScript

Guide of Random Code Generator JavaScript – Occasionally, programmers are required to produce a string that is generated by randomly picking characters. The Random String Generator aids in the creation of a random string. By selecting characters at random. A simple character string or an alpha-numeric string can be used for this string.

In this chapter, you’ll learn how to make a random string generator using several ways. To generate a random string. We’ll use the JavaScript programming language to develop random string generator software. It will produce a new string each time. We’ll utilize JavaScript’s Math.random() function for this.

Use of Random String generator

Most of the time, the captcha code is required to be entered. Before completing a web form in order to verify that the users are not robots. This Captcha code for programmers can be created with the help of the Random String Generator. It is now frequently used in web forms for security reasons.

Keep in mind that the Captcha code is made up of a series of random characters. It could be a blend of alpha-numeric and alphabetic characters.

Type of Random String Generators

There are two different types of random string generators:

  1. Simple random code generator
  2. Generate random alphanumeric string

These are the two sorts of string generators we have. We’ll make a JavaScript random string generator. That only generates alphabetic strings in this first type of random string generator.

The second sort of string generator, on the other hand. Will be a JavaScript program that generates random alpha-numeric strings. See the following examples for both string generators:

Simple random code generator

We’ll make a program to produce a random string here:

1st Approach: This method generates a simple random string. By randomly picking characters of the provided length. Instead of an alpha-numeric string, this will be a basic string. To get started, follow the steps below:

  • Create a user-defined function. Using all English alphabets in tiny and capital letters as a variable.
  • Define the length of the new randomly generated string.
  • Declare a new empty variable. To retain the generated string (var randomStringGenerator = “;).
  • Now, using the for loop, traverse the string. During each iteration, a new character will be generated.
  • Use the JavaScript Math.random() method. To produce a random character from the string variable (A-Z, a-z) by computing a random index inside this loop. Use the floor() method to round off the number. Math.floor(Math.random() * characters.length) will be utilize.

To observe the effect, convert the above stages into actual code implementation. Take a look at the following JavaScript code:

<html>  
<head>   
<title> Random String Generator </title>  
</head>  
  
<script>  
function randomStringGenerator() {  
    var characters = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";  
              
            //specify the length random new string  
    var lenString = 8;  
    var randomstring = '';  
  
    for (var i=0; i<lenString; i++) {  
        var rnum = Math.floor(Math.random() * characters.length);  
        randomstring += characters.substring(rnum, rnum+1);  
    }  
  
    document.getElementById("randomfield").innerHTML = randomstring;  
}  
</script>  
  
<body>  
<center>  
<h2 style="color: red"> Random String Generator </h2>  
<h3> Click the button to generate a new random string </h3>  
  
<form name="randomstring">  
<input type="button" value="Generate " onClick="randomStringGenerator();">  
<br><br>  
<b><p id="randomfield" style="color: blueviolet"> </p></b>  
</form>  
  
</center>  
</body>  
</html>  

Output:

Random Code Generator img1
Outcome before clicking

Click ‘Generate button to generate a new string

Random Code Generator img2
Output after 1st click
Random Code Generator img3
Output after 2nd click

Generate random alphanumeric string Approach one

To generate a random alpha-numeric string. Use one of the two methods described below:

1st approach: This method generates an alpha-numeric string of a predetermined length. The steps are as follows:

  • Make a user-defined function that contains all of the following stages.
  • Var alphaNumChars = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyzabcdefghiklmnopqrstuvwxyzabcdefghiklmnopqrstuvwxyzaabcdefghiklmnopqr”.
  • Set the length of the new randomly produced string.
  • To hold the newly produced string. Declare a new empty variable (var randomStringGenerator = “;).
  • Utilize the for loop to traverse the string. During each cycle, it will create a new character.
  • Calculate a random character from the above-specified string variable. (A-Z, a-z) using JavaScript’s Math.random() method inside this loop.
  • Use the JavaScript Math.random() method. To select a random character from the string variable (A-Z, a-z) by computing a random index inside this loop. Use the floor() method to round off the number. Math.floor(Math.random() * characters.length) will be utilize.

To observe the effect. Convert the above stages into actual code implementation.

<html>  
<head>   
<title> Random Alpha numeric String Generator </title>  
</head>  
  
<script>  
function randomString() {  
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";  
  
    var string_length = 8;  
    var randomstringGenerator = '';  
  
    for (var i=0; i<string_length; i++) {  
        var rnum = Math.floor(Math.random() * chars.length);  
        randomstringGenerator += chars.substring(rnum,rnum+1);  
    }  
    document.getElementById("randomfield").innerHTML = randomstringGenerator;  
}  
</script>  
  
<body>  
<center>  
<h2 style="color: green"> Random Alpha Numeric String Generator </h2>  
<h3> Click the button to generate a random alpha-numeric string </h3>  
  
<form name="randform">  
<input type="button" value="Generate" onClick="randomString();">  
<br><br>  
<h4 id="randomfield" style="color: green"> </h4>  
</form>  
</center>  
</body>  
</html>

Output:

Random Code Generator img4
Outcome before clicking
img5
Output after 1st click
img6
Output after 2nd click

Generate random alphanumeric string Approach two

Approach 2: We now have a second method. For generating an alpha-numeric string of the given length. It’s a quick and easy way to produce a random string. This does not necessitate a lot of complicated code. We won’t mention the length of the freshly created string in this method. It will require a new string of length 10 or 11.

To make a random alpha-numeric string, follow these simple steps:

  • Create a user-defined function that contains all of the steps listed below.
  • To begin, produce a random number with the random() function.
  • Now we’ll use the JavaScript toString(36) built-in method to convert the base to 36 (26 chars + 0 to 9). There are 26 alpha-numeric characters in these 36 characters. Finally, use slice() to extract the portion of the text that begins at position 2.

To observe the effect, convert the above stages into actual code implementation.

<html>   
<head>   
    <title>   
    Generate random alpha-numeric string using JavaScript   
    </title>   
</head>   
  
<body>   
  
<center>  
<h2 style="color:green;"> Random String Generator  </h2>   
      
<h3> Click the button to generate random alpha-numeric string </h3>  
<button onClick="random_String_Generator()"> Generate String </button>   
  
<p id="random_String" style="color: green;   
            font-size: 22px; font-weight: bold;"> </p>   
  
<script>   
    var result = document.getElementById('random_String');   
    function random_String_Generator() {   
        result.innerHTML = Math.random().toString(36).slice(2);   
    }   
</script>   
</center>  
  
</body>   
</html>  

Output:

img7
Outcome before clicking
img8
Output after clicking

Conclusion

Note: In approach 1, you can specify the new random string’s length (number of characters). However, in approach 2, you are unable to specify the length of the new string that will be form. Use any of these strategies on your website, depending on your needs.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. How to Print JavaScript Number Format with Commas?
  2. What is the Callback Function in JavaScript?

Leave a Comment