Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionScript 3 .replace() only replaces first instance

In Flash ActionScript 3, I am trying to do something I thought was simple: replace all instances of a phrase in a text string with another phrase. However, for some reason only the first instance is replaced and the rest ignored. I hacked a solution together by running it through the string replace function around 9 times so the end result has all the <br /> replaced but I'd like to know what I've done wrong. Thanks in advance!

My Code:

var importPostAddress = "123 Fake Street<br />Mytown<br />Mycounty<br />Mycountry<br />PO5 7CD<br /><br />";
var postAddress = importPostAddress.replace("<br />",", ");

Expected result when tracing postAddress:

123 Fake Street, Mytown, Mycounty, Mycountry, PO5 7CD, , 

Actual result:

123 Fake Street, Mytown<br />Mycounty<br />Mycountry<br />PO5 7CD<br /><br />
like image 706
Craig Avatar asked Mar 21 '12 14:03

Craig


1 Answers

In order to fix this, you need to do juuuust a little bit more work.

var importPostAddress = "123 Fake Street<br />Mytown<br />Mycounty<br />Mycountry<br />PO5 7CD<br /><br />";
var pattern:RegExp = /<br \/>/g;
var postAddress = importPostAddress.replace(pattern,", ");

I'm using a RegExp in order to pass the /g flag, which makes the replacement global (replace all instances of the expression found). I also had to escape the / in <br /> using a backslash \, as its a control character in regular expressions.

like image 83
Sam DeHaan Avatar answered Sep 21 '22 04:09

Sam DeHaan