I had cause recently to dust off an old ColdFusion tag to cfscript function conversion I did some time ago. I had trouble finding it amongst all my legacy projects. When I found it I thought I’d capture it here so I stood a better chance of finding it next time!
It's based on a random string generator originally written by the prolific Ben Nadel.
I named it getRandomString() as it truly only returns a random string which I happen to, in this case, be using as a system generated password.
public string function getRandomString(required numeric length) {
var lowerCaseAlpha = "abcdefghjkmnpqrstuvwxyz";
var upperCaseAlpha = "ABCDEFGHJKMNPQRSTUVWXYZ";
var numbers = "23456789";
var otherChars = "!@#$%^*";
var allValidChars = lowerCaseAlpha & upperCaseAlpha & numbers & otherChars;
var stringArray = [];
stringArray[1] = mid(numbers,randRange(1, len(numbers)), 1);
stringArray[2] = mid(lowerCaseAlpha, randRange(1, len(lowerCaseAlpha)), 1);
stringArray[3] = mid(upperCaseAlpha, randRange(1, len(upperCaseAlpha)), 1);
for (var intChar=1; intChar LTE arguments.length; ++intChar) {
stringArray[intChar] = mid(allValidChars, randRange(1, len(allValidChars)), 1);
}
createObject("java", "java.util.Collections").Shuffle(stringArray);
var randonString = arrayToList(stringArray, "");
return randonString;
}