views:

2063

answers:

4

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with Javascript?

+14  A: 

I think this will work for you:

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}
csharptest.net
This was what I was going to say :( I was not going to give him the function but just tell him how to get there
AntonioCS
Had this already lying around ;)
csharptest.net
+1  A: 

Something like this should work

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
     var randomPoz = Math.floor(Math.random() * charSet.length);
     randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

Call with default charset [a-zA-Z0-9] or send in your own:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');
Chad
+3  A: 
function randomstring(L){
    var s= '';
    var randomchar=function(){
     var n= Math.floor(Math.random()*62);
     if(n<10) return n; //1-10
     if(n<36) return String.fromCharCode(n+55); //A-Z
     return String.fromCharCode(n+61); //a-z
    }
    while(s.length< L) s+= randomchar();
    return s;
}

alert(randomstring(5))

kennebec
A: 

This works for sure

<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>
Vignesh