generate random Strings in AS2 or AS3

I was searching for a function to generate random Strings either in AS2 or in AS3 but I couldn't find any so I made my own using code from a typewriter effect, but I can't seem to find the page anymore. I use this code when I load dynamic content from php and such and I don't want flash to cache my request. Here is an ActionScript 2 version of the code:

Actionscript:
  1. function generateRandomString(newLength:Number):String{
  2.   var a:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  3.   var alphabet:Array = a.split("");
  4.   var randomLetter:String = "";
  5.   for (var i:Number = 0; i <newLength; i++){
  6.     randomLetter += alphabet[Math.floor(Math.random() * alphabet.length)];
  7.   }
  8.   return randomLetter;
  9. }

For the ActionScript 3 version of it I made some optimizations and I created a class with the static method in it here is the code:

Actionscript:
  1. package net.zedia.utils{
  2.   public final class StringUtils{
  3.     public static function generateRandomString(newLength:uint = 1, userAlphabet:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):String{
  4.       var alphabet:Array = userAlphabet.split("");
  5.       var alphabetLength:int = alphabet.length;
  6.       var randomLetters:String = "";
  7.       for (var i:uint = 0; i <newLength; i++){
  8.         randomLetters += alphabet[int(Math.floor(Math.random() * alphabetLength))];
  9.       }
  10.       return randomLetters;
  11.     }
  12.   }
  13. }

here is how you use it:

Actionscript:
  1. import net.zedia.utils.StringUtils;
  2.  
  3. trace (StringUtils.generateRandomString(4));//for a random string of 4 characters
  4.  
  5. trace (StringUtils.generateRandomString(4, "ROGER"));//for a random string of 4 characters using only the following letters: ROGER

Cet article en Français

2 Responses to “generate random Strings in AS2 or AS3”

  1. Daniel Says:

    Hey, this is super helpful, thanks :)

  2. David Patrick Says:

    Thank you sooo much, you’re the best !!!!!

Leave a Reply


Close
E-mail It