Flex Logo on WhiteWhat?!?  I was shocked to learn that the latest Flex framework / Actionscript doesn’t have an equivalent for a replaceAll() on String.  I’m looking for a simple way to do replacements on a string.  Most of the languages that I’ve worked with have such a method or a library to provide that functionality.  PHP has the str_replace function, Java has a replaceAll() on java.lang.String, Python has it, C++ has libraries that readily provide this functionality, the System.String in the .NET framework(1.0,1.1,2.0, etc.) has a string#replace method, even in the RIA space, Silverlight has a replace method on System.String, as does JavaFX (java.lang.String).

After searching and reading for a while, the closest equivalent that I could find is a custom method that utilizes the split and join functionality like the following:

public static function StringReplaceAll( source:String, find:String, replacement:String ) : String
{
    return source.split( find ).join( replacement );
}

The preceding function came from Base64.as from Jason Nussbaum’s blog post about Base64 encoding/decoding.   Others have used similar functionality like this post on flexfanatic. Its definitely better than while loop.

I also found that it is possible to utilize a RegExp within the String#replace function as shown on SCRIBBLE IT.  Basically the code would look like:

var str:string = "Somesilly String. silly!";
str.replace(new RegEx("silly", "g") " awesome");

With this pattern it can still be a one-liner, which should preform better than the split/join methodology, but I am still shocked that such a standard method isn’t in the framework.  I am a bit surprised by this finding.  is there a better way?  A good StringUtil Library or something similar?

Leave a Reply