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
+8.7k Golang : Natural string sorting example
+8.4k Golang : Get currencies exchange rates example
+13.7k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+5.6k Golang : Validate credit card example
+4.2k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+20.1k Golang : Read directory content with filepath.Walk()
+4.1k Java : Human readable password generator
+9.4k Golang : Convert decimal number(integer) to IPv4 address
+16.1k Golang : Read binary file into memory
+3.8k Python : Delay with time.sleep() function example
+11.3k Golang : Date and Time formatting
+8.9k Golang : Find age or leap age from date of birth example