Craig
Craig

Reputation: 451

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

Upvotes: 17

Views: 31339

Answers (2)

Sam DeHaan
Sam DeHaan

Reputation: 10325

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.

Upvotes: 29

ToddBFisher
ToddBFisher

Reputation: 11590

Sam has a good solution, another one is:

postAddress = importPostAddress.split("<br />").join(",");

Upvotes: 22

Related Questions