Search and Replace in Flash/Flex

by Kevin Partner on 23rd August, 2007

ActionScript 3 is one of the few languages I’ve ever worked with that lacks a native search and replace string function. In earlier versions of ActionScript it was necessary to hand-write a function to achieve this but AS3 can do it, just not as easily as it should.

Not surprisingly, it’s a method of the string class called “replace”. If I wanted to find the first occurence of “abc” in a string called myString, and replace it with “xyz” I could do it like this:

var str:String = “This string has abc in it.”;
str.replace(“abc”, “xyz”);

Which is all well and fine except that, in nearly all cases when I use replace, I want to replace all occurences, not just the first one. To do this is a little more complicated and involves creating a Regular Expression object like this:

var myRegExp:RegExp=new RegExp(“abc”,”g”);
var str:String = “This string has abc abc abc in it.”;
str.replace(myRegExp, “xyz”);

This is hardly using Regular Expressions at all but it is making use of the “g” flag which tells the replace method to replace all occurences (it stands for “global”).

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Add to favorites

{ 1 comment… read it below or add one }

Zashkaser August 5, 2009 at 5:08 pm

I love these stories! Keep making them!

Leave a Comment

Previous post:

Next post: