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
+9k Golang : Accept any number of function arguments with three dots(...)
+10.4k Golang : Convert file unix timestamp to UTC time example
+4.9k Which content-type(MIME type) to use for JSON data
+5.5k Golang : fmt.Println prints out empty data from struct
+5.8k Unix/Linux/MacOSx : Get local IP address
+8.4k Golang : Count leading or ending zeros(any item of interest) example
+14.6k Golang : Overwrite previous output with count down timer
+9.2k Golang : Intercept and compare HTTP response code example
+12.4k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+13.3k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+16.4k Golang :Trim white spaces from a string
+17.4k Golang : How to tell if a file is compressed either gzip or zip ?