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
+10.4k Golang : Convert file content to Hex
+10.3k Golang : Random Rune generator
+25.8k Golang : convert rune to integer value
+5.8k Fix yum-complete-transaction error
+7.6k Golang : How to handle file size larger than available memory panic issue
+62.9k Golang : Convert HTTP Response body to string
+36.1k Golang : Smarter Error Handling with strings.Contains()
+9.7k Golang : Copy map(hash table) example
+24.2k Golang : Upload to S3 with official aws-sdk-go package
+5.8k Golang : Struct field tags and what is their purpose?
+15.4k nginx: [emerg] unknown directive "ssl"
+9.1k Golang : automatically figure out array length(size) with three dots