Programming Example
Create random character using Javascript
Create random character using Javascript. This code will help you to generate random character with a specific length.
<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;
}
above code will produce random character of a specific length.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.