Generate a string of random characters

Here's a quick function for all those occasions when you need to generate a string of random characters in javascript.

  1. /**
  2.  * Generate a string of random characters of the specified length
  3.  *
  4.  * @param int length   Length of the string to generate
  5.  * @param bool nodupes Set to true if duplicate characters should not be allowed
  6.  * @return string
  7.  */
  8. function getRandomString(length, nodupes)
  9. {
  10.     // "typecast" the length to an integer
  11.     length = parseInt(length, 10);
  12.  
  13.     // make sure the output is at least one character long
  14.     if (length < 1) {
  15.         length = 1;
  16.     }
  17.  
  18.     // list of characters to use
  19.     var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  20.  
  21.     // final output string
  22.     var output = '';
  23.  
  24.     // list of used characters (only used if nodupes === true)
  25.     var used = '';
  26.  
  27.     // make sure we don't have an infinite loop
  28.     if ((nodupes === true) && (length > chars.length)) {
  29.         length = chars.length;
  30.     }
  31.  
  32.     // loop as many times as `length` defines
  33.     do {
  34.         // get a random number between 0 and length of `chars`
  35.         var randnum = Math.floor(Math.random() * chars.length)
  36.  
  37.         // extract the random character
  38.         var chr = chars.charAt(randnum);
  39.  
  40.         // check if we are not allowed to include duplicate characters
  41.         if (nodupes === true) {
  42.             // true if character already used
  43.  
  44.             var added = (used.indexOf(chr) !== -1);
  45.  
  46.             // skip the character if already used
  47.             if (added === true) {
  48.                 continue;
  49.             }
  50.  
  51.             // add character to the list of used ones
  52.             used += chr;
  53.         }
  54.  
  55.         // add character to the output string
  56.         output += chr;
  57.     } while (output.length < length);
  58.  
  59.     return output;
  60. }

The first parameter lets you specify the length of the resulting string. For example, if you set it to 20, you will get a string with 20 random characters in it (note - the string may contain repeating characters, i.e. any character could be encountered in the string more than one time).

If the second parameter is set to true, none of the characters in the string will be repeated more than once.

Hope it helps!

Comments
1
Helped me!
AJ, November 3rd 2012, 8:12
2
Glad to hear that!
Andris, November 22nd 2012, 15:48
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments