Useful String Functions
Hello and welcome to today's tutorial, where we will be taking a 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.
Joining together strings - If you want to join strings together, the easiest way is to use the + sign, which will run two strings into each other.
trace("Hello " + "and" + " welcome");//Traces: "Hello and Welcome"
You can also include numbers, which Flash will automatically turn into string format, as long as a string is present:
trace("How many fish? " + 5);//traces: "How many fish? 5" trace(12 + 34);//Traces "46" trace("" + 12 + 34);//traces: "1234"
You can also use the concat function to add stuff on, or just +=. concat does change the original string, but += is shorter and simpler:
var original:String = "Hey there!" var modified:String = original.concat(" Good day to you!"); trace(modified)//Traces "Hey there! Good day to you!" trace(original)//Hasn't changed original += " Nice to meet you!"; trace(original);//Has changed to "Hey there! Nice to meet you!"
Putting things in lower case or UPPER CASE - this is a relatively simple process, but is very useful when you are dealing with case sensitive stuff such as searches and replaces (which we will be covering later). You just use toLowerCase() or toUpperCase() as demonstrated here:
var example:String = "a mixture OF CASES"; trace(example.toLowerCase());//traces "a mixture of cases" trace(example.toUpperCase());//traces "A MIXTURE OF CASES" trace(example);//Hasn't changed //if you want it to: example = example.toLowerCase(); trace(example);//traces "a mixture of cases"
Replacing within Strings - The new, AS3 only, quick and easy way to replace stuff within strings, which is terribly useful sometimes. The replace function takes only two arguments - what to find, and what to replace it with, like the Find: and Replace with: boxes in a certain well known word processer.
For all of you familiar with regular expressions, you can use that as the Find: part and do something extra stuff in the Replace With: part, but maybe we'll look at that in a later tutorial, I don't know. In some ways it works similarly to the case changes, as it leaves the original untouched:
var example:String = "Foundation Flash is great"; trace(example.replace("great","even better than before")); //Traces "Foundation Flash is even better than before" trace(example) //Hasn't changed example = example.replace("great","fab"); //Now it has trace(example); //traces "Foundation Flash is fab" trace(example.replace("foundation flash","The site")); //doesn't do anything, it is case sensitive trace(example.toLowerCase().replace("foundation flash","The site")); //That's better
Well, three key things to do with strings that I can tick off. I'm not sure how these work in AS2, but quite frankly, I don't care. If you do care, contact us. Meet me next time for getting depths and removing things,