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
+4.3k Golang : Spell checking with ispell example
+12.5k Golang : How do I get the local IP (non-loopback) address ?
+20.8k Golang : GORM read from database example
+4.1k Golang : Handling image beyond OpenCV video capture boundary
+13.1k Golang : How to force compile or remove object files first before rebuild?
+9.5k Golang : Compress and decompress file with compress/flate example
+13.9k Golang : Compare floating-point numbers
+6k Golang : Convert(cast) []byte to io.Reader type
+14.5k Golang : Logging with logrus
+8k Golang : Bubble sort example
+8k Generate Random number with math/rand in Go
+27.4k Golang : Convert []string to []byte examples