Posts Tagged random Strings

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:

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

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:

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

here is how you use it:

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

Cet article en Français

, , ,

28 Comments