Tim’s
Bandwagon

ActionScript trim function

ActionScript 2.0 doesn’t have a trim function to strip whitespace from the start and end of a string. Here’s a simple function I wrote because I couldn’t find a satisfactory example on Google!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function trim(str:String):String
{
    var stripCharCodes = {
        code_9  : true, // tab
        code_10 : true, // linefeed
        code_13 : true, // return
        code_32 : true  // space
    };
    while(stripCharCodes["code_" + str.charCodeAt(0)] == true) {
        str = str.substring(1, str.length);
    }
    while(stripCharCodes["code_" + str.charCodeAt(str.length - 1)] == true) {
        str = str.substring(0, str.length - 1);
    }
    return str;
}

The horrible "code_" prefix hack is there because I don’t think there’s a native way to search an array or object for a key or value in ActionScript.

Update: just found this function at: frogstyle.ch. This one does a similar thing, but strips more characters.

1
2
3
4
5
6
function trim(str:String):String
{
    for(var i = 0; str.charCodeAt(i) < 33; i++);
    for(var j = str.length-1; str.charCodeAt(j) < 33; j--);
    return str.substring(i, j+1);
}

8 Comments

  1. This function has been a great help. Thanks!!!

  2. Thanks for valuable fucntion …it saves lot of time to write again !

  3. Thanks man!

  4. It worked for me. Great Code. Thanks for sharing.

  5. Thanks! This is short and clean: The way it should be.

  6. Thanks a lot! It really helps and works from the forst eseye! Спасибо

  7. Thks for this good code snippet!

  8. Thanks , nice trim methods.

Leave a Comment

Your personal information

Your comment