Javascript : Generate random key with specific length
Tags : javascript random-string
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.
Tags : javascript random-string
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
+1.9k AWS S3 : Prevent Hotlinking policy
+4.2k Golang : How to profile or log time spend on execution?
+13.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+2.3k Golang : Ackermann function example
+7.6k Golang : convert(cast) float to string
+3.2k Javascript : How to check a browser's Do Not Track status?
+3.6k Golang : Populate or initialize struct with values example
+2.9k Golang : Heap sort example
+5.9k Golang : Get RGBA values of each image pixel
+1.2k Golang : Frobnicate or tweaking a string example
+1.9k Golang : How to check variable or object type during runtime?
+14.6k Golang : Read directory content with filepath.Walk()