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.7k How to check with curl if my website or the asset is gzipped ?
+16.1k Golang : XML to JSON example
+12.4k Golang : Count number of runes in string
+24.4k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+4.1k Golang : Calculate a pip value and distance to target profit example
+5k Golang : Use NLP to get sentences for each paragraph example
+4.8k Unix/Linux/MacOSx : Get local IP address
+6.1k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+4.3k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+13.7k Golang : Submit web forms without browser by http.PostForm example
+5.2k Golang : Calculate US Dollar Index (DXY)