Main Content

You are here:

More Useful String Functions

Hello and welcome to today's ActionScript tutorial, where we will be taking another break from more complicated matters to look at a couple of the things you can do with strings in AS3. For more about what a string is, visit the variables page.

Reversing a string - Alright, this technically isn't a string function, but it does affect strings. It's a string function combined with two array functions, but thanks must go to Curtis Morley who publicised this method, which has helped me on many occasions. Thanks Curtis! Anyhow, here it is in action:

var aString:String = "Foundation Flash";
trace(aString.split("").reverse().join(""));
//Traces hsalF noitadnuoF

If you need further explanation, regarding that, visit Curtis' blog using the link in the previous paragraph.

Checking whether a string contains another string - There are actually a lot of ways of doing this, but this is the quickest and easiest. It utilises the function indexOf(). It takes two arguments namely the string you want to look for, and an optional one, which is the starting point. The first should be a string (Case Sensitive); the second a number, 0 (right at the beginning; default) or greater.

If it cannot find the string, the function returns -1. Otherwise, it returns the index of the first time it found the string. Here are some examples:

var masterString:String = "Foundation Flash is great, all others are rubbish";
trace(String(masterString.indexOf("bad")));
//traces "-1" i.e. not found
trace(String(masterString.indexOf("great")));
//traces "20" i.e. found
trace(String(masterString.indexOf("great",26)));
//traces "-1" i.e. not found (after the 26th character (','))
trace(String(masterString.indexOf("Foundation")));
// traces "0"
trace(String(masterString.indexOf("flash")));
//traces "-1" i.e. not found
trace(String(masterString.toLowerCase().indexOf("flash")));
//traces "11" i.e. found

Get a single character - Nice and simple this one is. To retrieve one character, we can use the charAt(). It only accepts one argument, the index of the the character. This is done as if the string were an array (actually pretty close to the way it perceives strings). This means the first character is character 0, and the last can be accessed using (myString.length - 1). The function then returns that character:

var myString:String = "Foundation Flash";
trace(myString.charAt(0));//F
trace(myString.charAt(1));//o
trace(myString.charAt((myString.length - 1)));//h

And there you have it: three more useful functions for you to enjoy,

Harry.

Comments