Reputation: 1683
One of my classes need this simple function to work:
private function indexOfCode(txt:String, charcode:int, ini:int=0):int {
for(var i:int=ini; i<txt.length; i++){
if(txt.charCodeAt(i)==charcode) return i;
}
return -1;
}
Just like String.indexOf, but searching for a code (I'm searching for control codes like line feed).
In JavaScript I'd extend String class using prototype. In AS3 it seams this is an "old fashion" practice, but creating another custom class for a custom class seams to much. Is there a simple way to extend String? Any other suggestion?
Upvotes: 1
Views: 308
Reputation: 36127
Please make sure that your prototype code complier need to crossed/execute at least once before call prototype functions.
String.prototype.indexOfCode = function(txt:String, charcode:int, ini:int=0):int
{
for(var i:int=ini; i<txt.length; i++)
{
if(txt.charCodeAt(i)== charcode) return i;
}
return -1;
}
var letters:String = "ABCDEFG";
trace("indexOfCode :: " + letters.indexOfCode(letters,67,0)); //Complier error if strict mode
trace("indexOfCode :: " + letters["indexOfCode"](letters,67,0)); //No error
Problem:
Basically we can't extend String class because it is sealed class in actionscript.
Upvotes: 0
Reputation: 6258
you can do it via some class with static method e.g. StringUtils.indexOfCode();
or you could make global function like so:
package
{
public function indexOfCode(txt:String, charcode:int, ini:int=0):int
{
for(var i:int=ini; i<txt.length; i++)
{
if(txt.charCodeAt(i)==charcode) return i;
}
return -1;
}
}
Upvotes: 1