Replacing Strings in AS3
Although this may be pretty basic - when it comes to dealing with strings, one of the most valuable methods is no doubt the split().join().
So let’s first go over split().
This is from adobe’s live docs:
split(delimiter:String, [limit:Number]) : Array
Split has two Parameters:
delimiter:String - A string; the character or string at which my_str splits.
limit:Number [optional] - The number of items to place into the array.
Ok - don’t get confused. Essentially if you have the string:
The first parameter (delimeter) is whatever character(s) you want to use for splitting the other characters up. So:
The second parameter basically tells split how many times you want to do it.
trace(myString.split(”%”, 4) // outputs: B , C , D
So a few really cool applications of this are:
1 - using it to parse out data.
2 - using it to replace or remove a string.
Let’s say you have some external data you are loading in - but you don’t want to use XML for some reason. You can separate your content by inserting a weird string of characters between your content:
var contentArray:Array = theContent.split(“#%?”);
trace(contentArray); // outputs: this is some content , and some more
The other option - the real money maker - is split().join()
This is the easiest way to replace things in a string.
theContent = theContent.split(“#%?”).join(“”);
trace(theContent); // outputs: this is some content and some more
For replacing strings:
theContent = theContent.split(“damn”).join(“darn”);
trace(theContent); // outputs: I hate when content has words like, ‘darn’ in it
About this entry
You’re currently hearting “Replacing Strings in AS3,” an entry on I h♥rt actionscript.
- 10.08.07 / 5pm