Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Friday, February 15, 2008

String Replace Function in Flex

I'm not sure if this is a redundant function or not. I know that Flex String objects have a replace() method but as far as I can tell this only replaces the first match and not every match in a string.

Here is an actionscript function for flex which works the same as the php str_replace() function.

str_replace( needle, replacement, haystack ) in ActionScript

public function str_replace(needle:String, replacement:String, haystack:String):String
{
var strArr:Array = haystack.split(needle);
return strArr.join(replacement);
}


If this is a pointless function and there is an easier way to accomplish this built into flex I would love to hear about it. I looked over the language reference documents and couldn't find something.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. You can also use the global flag g at the end of your regular expression.

    ReplyDelete
  3. var myPattern:RegExp = /sh/g;
    var str:String = "She sells seashells by the seashore.";
    trace(str.replace(myPattern, "sch"));

    ReplyDelete

Thank you for the comments.