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
+6.6k Golang : calculate elapsed run time
+14.7k Get file path of temporary file in Go
+5.5k Golang : Split strings into command line arguments
+3.5k Golang : Get SPF and DMARC from email headers to fight spam
+3.3k Android Studio : Indicate progression with ProgressBar example
+2.5k Golang : Sort lines of text example
+4.5k Golang : Allow Cross-Origin Resource Sharing request
+2.4k Golang : Rot13 and Rot5 algorithms example
+3.7k Golang : Inject/embed Javascript before sending out to browser example
+8.9k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+6.6k Golang : Chunk split or divide a string into smaller chunk example
+4.2k Golang : Get today's weekday name and calculate target day distance example