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
+37.6k Golang : How to read CSV file
+23.5k Golang : Get current file path of a file or executable
+6.3k Golang : Scanf function weird error in Windows
+4.2k Golang : The Tao of importing package
+6.9k Swift : Convert (cast) String to Float
+5.1k Linux/Unix : Commands that you need to be careful about
+19.7k Golang : Get password from console input without echo or masked
+5.5k Golang : Skip or discard items of non-interest when iterating example
+6.1k Golang : Use modern ciphers only in secure connection
+5.1k Javascript : Get operating system and browser information
+5.6k PHP : Shuffle to display different content or advertisement
+22.1k Golang : Print out struct values in string format