ActionScript 3 .replace() only replaces first instance

Craig picture Craig · Mar 21, 2012 · Viewed 28.9k times · Source

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 />

Answer

Sam DeHaan picture Sam DeHaan · Mar 21, 2012

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.