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.8k MariaDB/MySQL : Form select statement or search query with Chinese characters
+7k Golang : Levenshtein distance example
+17.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+7k Golang : Takes a plural word and makes it singular
+11.5k Golang : Generate DSA private, public key and PEM files example
+16.4k Golang :Trim white spaces from a string
+7.3k Golang : How to iterate a slice without using for loop?
+23k Golang : Test file read write permission example
+33.9k Golang : Call a function after some delay(time.Sleep and Tick)
+10.3k Golang : Embed secret text string into binary(executable) file
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+7.5k Golang : Process json data with Jason package