Sometimes we want to remove whitespace from the ends of our strings. In fact, this task is so common on the web that the ubiquitous jQuery library includes a utility method for that purpose.

What about in ActionScript 3? Well, not so much. The String class in AS3 is, in my opinion, a bit lacking compared to languages like C# and Scala. What's worse, you can't augment prototypes easily like you can in JavaScript to add missing methods (see update at the end for more information on this).

So I needed to trim a string in AS3. A quick Google search showed a couple so-so methods. Then I got to thinking: Hey, doesn't jQuery have a trim method? Aren't they both ECMAScript languages? Shouldn't something as basic as this be pretty similar in both languages?

The answer was yes to all those questions. So I popped open the jQuery source and did a quick search and found this a few lines into it:

// Used for trimming whitespace
rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,

Perfect. I created a StringHelper AS3 file, plunked it in, and presto, we have an efficient trimmer in AS3:

public final class StringHelper
{               
    public function StringHelper() { }
   
    public static function trim(str:String):String {
        return str.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "")
    }

    public static function trimStart(str:String):String {
        return str.replace(/^(\s|\u00A0)+/g, "");
    }

    public static function trimEnd(str:String):String {
        return str.replace(/(\s|\u00A0)+$/g, "");
    }
}

Update

After this was posted on Reddit, theillustratedlife made the following comment regarding the prototype chain in ActionScript:

You are supposed to be able to enhance the ECMAScript prototypes, but you might have to call a compiler flag when you do it. If you look in the docs, you'll notice that there are ECMAScript prototypes and interchangeable native code classes for the primitive types.

After doing a bit more experimenting, it looks like you can fairly easily augment the prototype chain in ActionScript as well. However, there are some caveats when running AS3 in strict mode. For example, consider having the String class augmented like so:

String.prototype.trim = function():String {
    return StringHelper.trim(this);
}

If we try to call the trim() method in the usual way

var str:String = "foo";
str.trim();

we'll get a compile-time error because the AS3 compiler can't find the method in the String class definition. Fortunately, we can get around this by using a dynamic reference

var str:String = "foo";
str["trim"]();

It's a lot uglier, but it works.