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 />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With