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
+8k Golang : Go as a script or running go with shebang/hashbang style
+14.4k Golang : Loop each day of the current month example
+7.8k Golang : Get curl -I or head data from URL example
+14.1k Golang : Get query string value on a POST request
+50.5k Golang : How to get time in milliseconds?
+22.8k Golang : Daemonizing a simple web server process example
+7.1k Golang : Variadic function arguments sanity check example
+7.6k Linux/Unix : fatal: the Postfix mail system is already running
+7.9k Golang : Get SPF and DMARC from email headers to fight spam
+6.5k Golang : What fmt.Println() can do and println() cannot do
+5.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem