17

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 />
cf-
  • 8,598
  • 9
  • 36
  • 58
Craig
  • 431
  • 1
  • 4
  • 12

2 Answers2

29

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.

Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48
  • Hi Sam thanks for your reply. Do you use `/` instead of quotes for defining a string?? Does this effectively say: `var pattern:RegExp = "
    "g;` ? or `"
    "/g;`
    – Craig Mar 23 '12 at 10:21
  • @CraigMcArthur You use `/` instead of quotes for defining a `RexExp`. This basically says replace the pattern (in this case the pattern has no special regex characteristics, so it's practically a String) `
    ` **globally**.
    – Sam DeHaan Mar 23 '12 at 12:24
22

Sam has a good solution, another one is:

postAddress = importPostAddress.split("<br />").join(",");
ToddBFisher
  • 11,370
  • 8
  • 38
  • 54
  • 1
    For me this is the only solution, **for** it's a pain in the ... to replace all strings that are **not hard-coded** into your code with RegExp. Maybe I want to replace `n`, maybe `backslash` or maybe the **user** wants to enter random characters that I need to remove from the strings. – Bitterblue Dec 16 '14 at 13:49