Monthly Archives: December 2010

another way to generate random string in javascript

i have searched “javascript generate random string” in web with google and all results from first page (with 10 results) are like this:
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>

as you see, it calls random function for each character. my browser firefox 3.6.12 and i think also other modern browsers generate big information by one random call, because it returned number with 17 digits after “0.”. i think even one call of random is probably heavy. so i have had idea to make random string using 1 random call, because it has enough random numbers for that. i have made this algorithm:
r=Math.random()*100000000000000000;
ch='әөүҗңһабвгдежзийклмнопрстуфхцчщъыьеюя';
chl=ch.length;
nick='';
newr=r;
while((r=newr)>=chl){
newr=Math.floor(r/chl);
nick+=ch.substr((r-newr*chl),1);
}

(after this “nick” value is random string).