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
+21.9k Golang : Join arrays or slices example
+9.2k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+32.1k Golang : Convert []string to []byte examples
+11.4k Swift : Convert (cast) Float to String
+13.3k Golang : Count number of runes in string
+40.1k Golang : Convert to io.ReadSeeker type
+13.9k Golang : Compress and decompress file with compress/flate example
+8k Android Studio : Rating bar example
+7.8k Swift : Convert (cast) String to Float
+12.6k Golang : zlib compress file example
+12.5k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+8.4k Android Studio : Import third-party library or package into Gradle Scripts