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
+26.1k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+29.1k Golang : Get first few and last few characters from string
+5k Google : Block or disable caching of your website content
+11.2k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+8.5k Golang : Ackermann function example
+7.5k Golang : Process json data with Jason package
+10.7k Android Studio : Simple input textbox and intercept key example
+14.6k Golang : How to check if your program is running in a terminal
+9.8k Golang : Load ASN1 encoded DSA public key PEM file example
+81.2k Golang : How to return HTTP status code?
+5.9k Golang : Use NLP to get sentences for each paragraph example
+8.1k Golang : Get all countries phone codes