Home / Programs / Create random character using Javascript
Programming Example

Create random character using Javascript

👁 333 Views
💻 Practical Program
📘 Step by Step Learning
Create random character using Javascript. This code will help you to generate random character with a specific length.

Program Code

<html>
<body>
<div>
Enter the length of character:
<input type='text' id="num">
<button onclick="stringGen()">submit</button>
<p id="result"></p>
</div>
<script type="text/javascript" src="index.js"></SCRIPT>
</body>
</html>


function stringGen()
{
  var length = document.getElementById("num").value;
  // alert(length);
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   document.getElementById("result").innerHTML = result; 
   return result;
}




Output

above code will produce random character of a specific length.

Explanation

No

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.