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
+16.4k Golang : Find out mime type from bytes in buffer
+6.6k Golang : Warp text string by number of characters or runes example
+7.9k Javascript : How to check a browser's Do Not Track status?
+11.8k Golang : GTK Input dialog box examples
+5.1k Swift : Convert (cast) Float to Int or Int32 value
+10k Golang : Convert octal value to string to deal with leading zero problem
+17.9k Golang : Simple client server example
+6.2k Golang & Javascript : How to save cropped image to file on server
+16.8k Golang : read gzipped http response
+5.7k Linux/Unix/PHP : Restart PHP-FPM