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.5k Generate Random number with math/rand in Go
+10k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+9.7k Golang : How to generate Code 39 barcode?
+8.6k Golang : Generate Datamatrix barcode
+18.1k Golang : Defer function inside init()
+10.2k Golang : Find and replace data in all files recursively
+5.8k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+13.5k Golang : Generate Code128 barcode
+12.5k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+12k Golang : Convert(cast) bigint to string
+9k Android Studio : Image button and button example