I need some help in adding the replace all functionality into my Flex project. I would prefer doing this in a way that is as natural as possible.
What I want to achieve is to be able to run this code (with the Flex compiler) "aabbaaba".replaceAll("b","c") and get "aaccaaca". Also I want to chain replaceAll calls.
Note: I won’t be actually replacing bs with cs, but various string that will not be known at coding time!
What I don’t want:
1. Use regular expressions with the global flag. The tokens to replace are determined ad run time and transforming them into a regular expression isn’t straight forward.
2. Use the StringUtil.replace method. It’s a static method and chaining is ugly.
3. Chain split and join. Because it may be confusing for others when reading the code.
4. Disable strict type checking. I want to have type checking for the rest of my code.
Here is what I have so far:
String.prototype.replaceAll = function(replace:String, replaceWith:String):String{
return this.split(replace).join(replaceWith);
}
And can be called like this:
"aababacaaccb"["replaceAll"]("b", "c")["replaceAll"]("c", "a");
Also, are there any recommendations against extending objects through the prototype? I will also accept an answer that has strong arguments against extending the String object through the prototype.
Thank you,
Alin
I think you got all the technical answers possible. I will elaborate in what I think is the best way to approach this language-wise.
Prototypes are not recommended in an OOP language such as AS3 (mostly because they defy encapsulation). You imply that you don’t want something “confusing to others” (in relation to split.join); well, prototypes in AS3 are very confusing.
Just as an example of this, a prototype declaration can be done from anywhere in your code, and as such is not obvious where it should reside. If “others” encounter “foo”.replaceAll() in your code, it’s not at all obvious where one can find that method and check what it really does.
A static function amends this and is pretty straight forward. Sure, you need an extra argument, and you can’t really chain properly, but is this such a bad thing?
If you need performance, split.join is the way to go. I would bet good money that more AS3 devs know about split.join than the use of prototypes.
On the other hand, I think the most semantic and pragmatic way would be to use the own language method (hence my previous answer). You are trying to replace all needles in a string with another string in AS3, and for that the language has the String::replace method with the global flag. I’m pretty sure there is a way to easily parse and use any string in regexp.
I concur that in some cases a helper method (like replaceAll) could be necessary, but I would strongly encourage you to not use prototypes, and instead use a more standard way, like StringUtil.replace.