phpactionscript-3oopflashflashdevelop

Does AS3 have a method similar to PHP's strtr()?


I need to replace some characters in a string. For example:

var str:String = 'Hello World!';

And I need to change all characters in this string using some table of comparison that is an array. In PHP I would use the strtr() method for this purpose. But I couldn't find its analog in AS3.

So, please help! How can I do this in AS3. Thanks in advance.


Solution

  • You can use replace function.

    If you want to change e (only first occurence)

    var str:String = "Hello world!";
    str = str.replace('e', 'x');
    

    Result will be:

    Hxllo world!
    

    If you want to change all occurences (for example you ewant to change all o)

    var str:String = "Hello world!";
    var pattern:RegExp = /o/g;
    str = str.replace(pattern, 'x');
    

    Result will be:

    Hellx wxrld!
    

    If you want to change all occurences case insensitive:

    var str:String = "Hello world!";
    var pattern:RegExp = /h/gi;
    str = str.replace(pattern, 'x');
    

    Result will be:

    xello world!