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
+32.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+5.1k PageSpeed : Clear or flush cache on web server
+4.9k Golang : Measure execution time for a function
+33.9k Golang : Get file last modified date and time
+39.7k Golang : How to check if a string contains another sub-string?
+9.8k Golang : Generate random elements without repetition or duplicate
+10.6k CodeIgniter : Import Linkedin data
+21.6k Golang : Calculate time different
+4.2k Python : Create Whois client or function example
+14.6k Golang : How to reverse elements order in map ?
+16.2k Golang : How to remove certain lines from a file
+4.1k Golang : Convert lines of string into list for delete and insert operation