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
+16k Golang : Defer function inside init()
+7.1k Golang : Emulate NumPy way of creating matrix example
+13.7k Golang : How to check if IP address is in range
+7k Golang : Append and add item in slice
+19.6k Golang : How to read float value from standard input ?
+19.8k Golang : Encrypt and decrypt data with TripleDES
+16.2k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+6k Golang : Get environment variable
+32.3k Golang : All update packages with go get command
+9.9k Golang : Delay or limit HTTP requests example
+7.6k Golang : Set or add headers for many or different handlers
+9.4k Golang : Flip coin example