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”).


.gif)
{ 1 comment… read it below or add one }
I love these stories! Keep making them!