Wednesday, September 21, 2011

ActionScript 3.0 Pad String Method

Problem: I use PHP a lot and am currently working on a project in ActionScript  (Flash Builder). I found myself needing a method similar to str_pad. I found a couple online, but nothing as powerful as the one provided in PHP.

Solution: Write my own... here it is. You will find it is very similar to PHP's str_pad method. Also note, there could be a couple improvements in padded string generation, but this will do for now.

/**
             * Add a number of padding in front or back of a string.
             * @param string:String - The string to pad
             * @param length:uint - The final length of the string
             * @param pad_string:String - The string to use as padding
             * @param pad_left:Boolean - padding front or back of string
             */   
            public function padString(input:String, pad_length:uint, pad_string:String, pad_left:Boolean = true):String
            {
                // return input if length greater than padded length
                if (input.length >= pad_length) return input;
               
                // generate padding
                var paddedString:String = "";
                for (var i:uint = 0; i < pad_length - input.length; i++)
                    paddedString += pad_string;
               
                // concatonate results
                var resultStr:String = pad_left ? (paddedString + input) : (input + paddedString);
               
                // account for overflow if any
                if (resultStr.length > pad_length){
                    // chop off extra from result based on pad_type
                    if (pad_left)
                        resultStr = resultStr.substr(resultStr.length - pad_length, resultStr.length);
                    else
                        resultStr = resultStr.substr(0, pad_length);
                }
                return resultStr;
            }