`

Tuesday, September 21, 2010

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:

var myString:String = % B % C % D % E % F;

The first parameter (delimeter) is whatever character(s) you want to use for splitting the other characters up. So:

trace(myString.split(%)); // outputs the array , B , C , D , E , F 

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 theContent:String = this is some content #%?and some more #%?
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.
for removal:

var theContent:String = this is some content #%?and some more #%?
theContent = theContent.split(#%?).join(“”);
trace(theContent); // outputs: this is some content and some more  

For replacing strings:

var theContent:String = I hate when content has words like, ‘damn’ in it
theContent = theContent.split(damn).join(darn);
trace(theContent); // outputs: I hate when content has words like, ‘darn’ in it  

No comments: