Here are some quick and easy solutions for trimming leading and trailing 0′s from a string in ActionScript. The examples that follow illustrate trimming leading 0′s from a string of numbers only, trimming leading 0′s from an alpha-numeric string, and trimming trailing 0′s from either a numeric or alpha-numeric string. All three are very simple to implement.
In the first problem, we need to trim the leading 0′s from a string of numbers, “00076925″ for example. This is easily accomplished using a simple parseFloat method:
private function trimLeading0sFromString() : void
{
var numericString:String = "00076925";
numericString = parseFloat ( numericString ).toString();
trace ( numericString ); // 76925
}
The next problem is a bit more complex, but nonetheless simple to solve and implement. In this case we need to trim the leading 0′s from a string of alpha-numeric characters, “000076925-B72A32″. We’ll implement a simple regular expression to do the work for us here because using parseFloat would leave us with a result of “76925″:
private function trimLeading0sFromString() : void
{
var alphaNumericString:String = "000076925-B72A32";
var pattern:RegExp = new RegExp ( '^0+' );
alphaNumericString = alphaNumericString.replace ( pattern,'' );
trace ( alphaNumericString ); // 76925-B72A32
}
A bit about this simple regex. We are using a couple of metacharacters to help us. The caret (^) metacharacter matches the beginning of a string. We are looking for a beginning of string match, using ^0, which says – look for a match of 0 at beginning of string. Lastly, the plus (+) metacharacter matches the previous item, in this case a 0, one or many times. In this way we can look for as many leading 0′s in a string and remove them using the replace method, which simply replaces the pattern match with an empty string.
Here in our last example, our problem is that we need to remove the trailing 0′s, this expression may be used for both numeric and alpha-numeric strings. Again, in this example we’ll use a regular expression to accomplish this:
private function trimTrailing0sFromString() : void
{
var alphaNumericString:String = "76925-B72A320000";
var pattern:RegExp = new RegExp ( '[0]+$' );
alphaNumericString = alphaNumericString.replace ( pattern,'' );
trace ( alphaNumericString ); // 76925-B72A32
}
Note the change to the regular expression. In this example we use the metacharacter [ and ] to create a character class. We are defining that we will match any number of 0′s that we may find, matching the previous item, “+” at the end of the string “$”.
