In order to generate a random string, we must first specify length of string and character set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function generateRandom(lengthOfString, charset) {
// The scope of the character
if(charset == null) charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
var rand = '';
while(lengthOfString > 0) {
/*
since the index of char is start from 0, so no need to +1 on the random number
we want the range from 0 - lengthOfString
*/
rand += charset.charAt(Math.floor(Math.random() * charset.length));
lengthOfString--;
}
return rand;
}

References: