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:
-
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:
Actionscript:
-
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:
Actionscript:
-
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
June 10th, 2008 at 1:59 pm
Hey, this is super helpful, thanks
June 13th, 2008 at 5:48 pm
Thank you sooo much, you’re the best !!!!!
October 20th, 2008 at 11:02 am
Ah, this saves me some work. Thanks for putting it online!
October 23rd, 2008 at 6:51 am
Thanks for that. Very handy. Already started work extending it to generate capitalised words. Next step phrases and Paragraphs.