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
+11.4k Golang : Calculations using complex numbers example
+7.9k Golang : HttpRouter multiplexer routing example
+5.8k Golang : Missing Subversion command
+6.6k Fix sudo yum hang problem with no output or error messages
+8.7k Golang : Inject/embed Javascript before sending out to browser example
+19.6k Golang : How to get time from unix nano example
+6.3k Unix/Linux : How to get own IP address ?
+4.4k Javascript : Access JSON data example
+20.1k Nginx + FastCGI + Go Setup.
+36.2k Golang : Display float in 2 decimal points and rounding up or down
+7.6k Javascript : Put image into Chrome browser's console
+7.8k Golang : Multiplexer with net/http and map