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
+5.1k Python : Convert(cast) string to bytes example
+12.6k Golang : http.Get example
+9.8k Golang : Get escape characters \u form from unicode characters
+5.8k Javascript : Get operating system and browser information
+6.9k Golang : Transform lisp or spinal case to Pascal case example
+8.7k Golang : Inject/embed Javascript before sending out to browser example
+22.6k Golang : Gorilla mux routing example
+15.7k Golang : How to reverse elements order in map ?
+10.4k Golang : How to delete element(data) from map ?
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+13.3k Golang : Query string with space symbol %20 in between
+16.5k Golang : Get the IPv4 and IPv6 addresses for a specific network interface