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
+12.6k nginx: [emerg] unknown directive "ssl"
+5.2k PHP : Shuffle to display different content or advertisement
+5.5k Golang : Dealing with postal or zip code example
+3.9k Javascript : How to loop over and parse JSON data?
+6.7k Golang : Intercept and compare HTTP response code example
+7.5k Golang : Qt get screen resolution and display on center example
+5.2k Golang : Calculate BMI and risk category
+12.1k Golang : Get current time
+6.5k Golang : Another camera capture GUI application with GTK and OpenCV
+5.3k Golang : Get Alexa ranking data example
+11.5k Golang : Send email with attachment(RFC2822) using Gmail API example
+4k Golang : Shortening import identifier