Random String Generator using JavaScript

At times, developers may need to generate a string comprised of randomly selected characters. A Random String Generator facilitates the creation of such a string by randomly picking characters. The resulting string can consist of either basic characters or a combination of letters and numbers.

This section presents various approaches for developing a tool that generates random strings. We will construct a random string generator application with JavaScript to produce unique strings upon each execution. The generation of random strings will rely on the utilization of JavaScript's Math.random function.

Use of Random String generator

Frequently, captcha codes are encountered in web forms as a means to authenticate users as human before they can submit the form. The Random String Generator is a tool that assists developers in generating such captcha codes. These codes are commonly utilized in web forms today to enhance security measures.

It's important to note that a Captcha code consists of a series of unpredictable characters. This sequence may consist of letters only, or a mix of letters and numbers.

Type of Random String Generators we discussed in this chapter

There are two variations of a random string generator available:

  • Create a basic Random String
  • Create an alpha-numeric Random String

There are two varieties of string generators available. The initial type involves a random string generator that is dedicated to producing alphabetic strings via a JavaScript program.

Conversely, within the second category of string generator, we will develop a JavaScript script to produce random alphanumeric strings. Refer to the detailed examples for both types of string generators below:

Generate a Random String

In this section, we will develop a script to produce a randomized string:

Approach 1:

This approach will create a simple random string by selecting some characters randomly with the specified length. This will be a simple string instead of an alpha-numeric string. Follow the steps below:

  • Create a user-defined function and define a variable having all English alphabets in small and capital letters.
  • Define the length for the new random string to be generated.
  • Declare a new empty variable (var randomstring = '';) to hold the generated string.
  • Now, traverse the string using for loop. It will generate a new character during each iteration.
  • Inside this loop, use Math.random method of JavaScript to generate a random character from the above-specified string variable (A-Z, a-z) by calculating a random index.
  • floor method to round off the value. This will be used as Math.floor(Math.random * characters.length).

Implement the preceding instructions into code to observe the outcome. Refer to the JavaScript snippet provided:

Copy Code

Example

<html>
<head> 
<title> Random String Generator </title>
</head>

<script>
function randomString() {
            //define a variable consisting alphabets in small and capital letter
	var characters = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            
            //specify the length for the new string
	var lenString = 7;
	var randomstring = '';

            //loop to select a new character in each iteration
	for (var i=0; i<lenString; i++) {
		var rnum = Math.floor(Math.random() * characters.length);
		randomstring += characters.substring(rnum, rnum+1);
	}

             //display the generated string 
	document.getElementById("randomfield").innerHTML = randomstring;
}
</script>

<body>
<center>
<h2 style="color: green"> Random String Generator </h2>
<h3> Click the button to generate a random string </h3>

<form name="randomform">
<input type="button" value="Generate Random String" onClick="randomString();">
<br><br>
<b><p id="randomfield" style="color: green"> </p></b>
</form>

</center>
</body>
</html>

Execute the code within your web browser to obtain the identical outcome displayed in the screenshot provided below:

Output 1

Output 2

Press the "Generate Random String" button to have a random string generated for you.

Output 3

Every time the button is clicked, it will produce a unique pattern of random characters, forming a random string that is 7 characters long. Please refer to the screenshot below for a visual representation:

Generate Random Alpha-Numeric String

Below are two methods that have been discussed for creating a random alphanumeric string:

Approach 1:

This approach will create an alpha-numeric string having a specified length. Follow the below steps:

  • Create a user-defined function having that will consist of all the below steps inside it.
  • Define a variable having all alpha-numeric characters in small and capital letters and from 0-9, e.g., var alphaNumChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";.
  • Define the length for the new random string to be generated.
  • Declare a new empty variable (var randomstring = '';) to hold the newly generated string.
  • Now, traverse the string using for loop. It will generate a new character during each iteration.
  • Inside this loop, use Math.random method of JavaScript to select a random character from the above-specified string variable (A-Z, a-z) by calculating a random index.
  • floor method to round off the value. This will be used as Math.floor(Math.random * characters.length).

Translate the aforementioned instructions into practical code implementation to observe the outcome. Examine the JavaScript snippet provided:

Copy Code

Example

<html>
<head> 
<title> Random String Generator </title>
</head>

<script>
function randomString() {
            //initialize a variable having alpha-numeric characters
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

            //specify the length for the new string to be generated
	var string_length = 8;
	var randomstring = '';

            //put a loop to select a character randomly in each iteration
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
             //display the generated string 
	document.getElementById("randomfield").innerHTML = randomstring;
}
</script>

<body>
<center>
<h2 style="color: green"> Random String Generator </h2>
<h3> Click the button to generate a random alpha-numeric string </h3>

<form name="randform">
<input type="button" value="Generate Alpha-numeric String" onClick="randomString();">
<br><br>
<h4 id="randomfield" style="color: green"> </h4>
</form>
</center>
</body>
</html>

Execute the code within your web browser to observe the output identical to the one displayed in the screenshot provided below:

Output 1

Output 2

Press the "Generate Random String" button to create a randomly generated string.

Output 3

Whenever you activate this button, it will produce a fresh series of random characters (random string) for you. Refer to the screenshot below:

Approach 2:

An alternative method involves creating an alphanumeric string of a certain length. This method offers a concise way to produce a random string without the need for extensive code. Unlike before, the length of the generated string is not predetermined and will typically be either 10 or 11 characters long.

Follow the basic steps to create a random alpha-numeric string:

  • Create a user-defined function having that will consists all the below steps inside it.
  • Firstly, use random method to generate a random number.
  • Now, we will use the built-in method of JavaScript toString(36) to convert the base to 36 (26 chars + 0 to 9). In these 36 characters it has alpha-numeric characters includes 26 alphabets and 0 to 9 numbers.
  • Finally, use the slice to get the part of string that is started from position 2.

Translate the aforementioned instructions into practical code to observe the outcome. Examine the JavaScript snippet provided:

Copy Code

Example

<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 1

Save the document and execute the code provided in your web browser. Initially, the output displayed will match what is shown in the following image:

Output 2

To produce a random alphanumeric string, simply press the "Generate String" button and observe the output.

Output 3

Every time you click on the "Generate String" button, a new unique pattern will be created. Click the button to explore various alphanumeric string patterns:

Note:

In the first method, you have the option to specify the size (character count) for the newly generated random string. However,

In the second approach, it is not possible to specify the exact length of the newly generated string. You can choose to implement any of these approaches on your website based on your specific needs.

Input Required

This code uses input(). Please provide values below: