Advertisement
carbonize

Random Characters

Feb 15th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function randomChrs(len) {
  2.   // Just an array of the characters we want in our random string
  3.   var chrs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  4.               'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  5.               '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
  6.              
  7.   // Check that a length has been supplied and if not default to 32
  8.   len = (isNaN(len)) ? 32 : len;
  9.  
  10.   // The following section shuffles the array just to further randomise the output
  11.   var tmp, current, top = chrs.length;
  12.   if(top)
  13.   {
  14.     while(--top)
  15.     {
  16.       current = Math.floor(Math.random() * (top + 1));
  17.       tmp = chrs[current];
  18.       chrs[current] = chrs[top];
  19.       chrs[top] = tmp;
  20.     }
  21.   }
  22.  
  23.   // Just a holder for our random string
  24.   var randomStr = '';
  25.  
  26.   // Loop through the required number of characters grabbing one at random from the array each time
  27.   for(i=0;i<len;i++)
  28.   {
  29.     randomStr = randomStr + chrs[Math.floor(Math.random()*chrs.length)];
  30.   }
  31.  
  32.   // Return our random string
  33.   return randomStr;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement