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
+10.6k Golang : Fuzzy string search or approximate string matching example
+45.1k Golang : Encode image to base64 example
+7.3k Golang : Tell color name with OpenCV example
+35.4k Golang : Convert date or time stamp from string to time.Time type
+12k Golang : Convert(cast) uintptr to string example
+5.5k Golang : Map within a map example
+6.1k Golang : Normalize email to prevent multiple signups example
+13.8k Golang : Save(pipe) HTTP response into a file
+4.1k JQuery : Calling a function inside Jquery(document) block
+11.6k Golang : HTTP response JSON encoded data
+13.5k Golang : Overwrite previous output with count down timer
+23.8k Golang : Create PDF file from HTML file