Function to Generate Random String using pre-defined Characters

Let’s talk about mobile verification code where we need to send a six digit random string to the user device for verify his/her mobile number. In this case it is wise to generate the random string using client script (JavaScript or Jquery) & can send a copy to the server using Ajax post method.

In the below example I created a function where you can generate any length of random string from the specific characters you want. In the configuration variable of randomString() function I declared chars as the list of characters you want for your random string. Here for a demo purpose I added numbers (0 to 9) & alphabets in both the case (Upper & Lower). Using the variable string_length you can set the length of your random string. In body part of HTML I have a button control with a div DisplayRandomString. Onclick of button Generate I am applying html to the div using Jquery. randomString() function returns randomstring variable as string. Which I am showing in the div on click event of button btnGenerate.

To run the below example copy the html codes into a notepad file. Save it as html. The jquery library I referred here is a CDN link. Before run the html file make sure you are with Internet Connectivity.

Generate Random String Example

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/*Generate button Click event*/
$('#btnGenerate').click(function() {
$('#DisplayRandomString').html(randomString());
});

/*Function to Generate Random String*/
function randomString() {
/*Charecters you want to use for your Random String*/
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
/*Length of the Random String you want to Generate*/
var string_length = 6;
var randomstring = '';

for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}

return randomstring;
}
});

</script>

</head>
<body>
<button id="btnGenerate">Generate</button>
<!--Div to Display Random String-->
<div id="DisplayRandomString"></div>
</body>
</html>