-3

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.

a2800276
  • 3,272
  • 22
  • 33
L6go1as
  • 39
  • 9

1 Answers1

1

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!
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
  • Thanks for your answer! But is there another ways ? Im asking because i have table of chars to replace and using RegExp in loop for replacing all characters in string by chars from table will cost me a lot of preformance (correct me if im wrong). – L6go1as Dec 16 '15 at 09:12
  • Have a nice day. If my answer accomplishes your question, please accept it ;) – Joe Taras Dec 16 '15 at 09:15
  • please read my edited post ) im looking forward to your seductions ) – L6go1as Dec 16 '15 at 12:03
  • you must define separated RegExp because your replace is different, letter by letter. If you want to change e with x, a with y and t with g you must apply three times the replace functions. You can create a method to factorize your code, but the way is that in my answer – Joe Taras Dec 16 '15 at 13:43
  • I see, I hoped that somewhere lies method that I could use like strstr(string_to_replace, array_of_chars). )) – L6go1as Dec 16 '15 at 14:06
  • A punctualization. The correct PHP function is str_replace not strstr. In PHP str_replace accepts as parameters two arrays (the first for search, the second for replace), so substritution goes in positional way. – Joe Taras Dec 16 '15 at 14:10
  • you are correct, but str_replace sometime do not work correclty, that why I used strtr() for purpose to 'replace' chars. – L6go1as Dec 16 '15 at 14:49
  • This is not correct answer. If I want, for example, to do php strtr for "Hello World" to change o to e, and e to o, I would use strtr("Hello World","eo","oe") and I'll get "Holle Werld" which is correct. With your idea, after first replacement e to o, and then o to e, I'll get "Helle Werld"... think about it. – Војин Петровић Sep 16 '18 at 11:02