Javascript : Generate random key with specific length
Was looking for a way to generate random string with Javascript today and also wanted to limit the random string length.
This code fragment below should do the job.
// define the characters to pick from
var chars ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz*&-%/!?*+=()";
// note if you are looking for random integer, use this instead
// var chars ="0123456789";
// specify the length with keyLength parameter
var generateKey = function generateKey(keyLength){
var randomStr = '';
for (var i=0; i < keyLength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomStr += chars.substring(rnum,rnum+1);
}
return randomStr;
};
Give this javascript a try when you want to generate random string value.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+23.5k Golang : Upload and download file to/from AWS S3
+2.5k Golang : Create new color from command line parameters
+3.5k Golang : Qt Yes No and Quit message box example
+7.3k Golang : syscall.Socket example
+16.1k Golang : Find biggest/largest number in array
+15k Golang : Change file read or write permission example
+6.4k Golang : How to check if IP address is in range
+2.5k Golang : Detect face in uploaded photo like GPlus
+7.6k Golang : Execute function at intervals or after some delay
+2.6k Golang : Return multiple values from function