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.2k Golang : Check if a string contains multiple sub-strings in []string?
+6k Linux/Unix : Commands that you need to be careful about
+4.7k Python : Find out the variable type and determine the type with simple test
+5.1k Golang : How to deal with configuration data?
+18.5k Golang : Display list of time zones with GMT
+8.9k Golang : Gonum standard normal random numbers example
+5k Golang : The Tao of importing package
+4.9k Golang : Display packages names during compilation
+16.6k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+16.8k Golang : XML to JSON example
+18.3k Golang : Write file with io.WriteString
+20.4k Golang : Read directory content with os.Open