string ActionScript 3 .replace() 只替换第一个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9806177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:25:43  来源:igfitidea点击:

ActionScript 3 .replace() only replaces first instance

stringactionscript-3

提问by Craig

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!

在 Flash ActionScript 3 中,我试图做一些我认为很简单的事情:用另一个短语替换文本字符串中一个短语的所有实例。但是,由于某种原因,只有第一个实例被替换,其余的被忽略。我通过大约 9 次通过字符串替换函数运行它来一起破解一个解决方案,因此最终结果已全部<br />替换,但我想知道我做错了什么。提前致谢!

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:

跟踪时的预期结果postAddress

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

Actual result:

实际结果:

123 Fake Street, Mytown<br />Mycounty<br />Mycountry<br />PO5 7CD<br /><br />

回答by Sam DeHaan

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 RegExpin order to pass the /gflag, 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.

我正在使用 aRegExp来传递/g标志,这使替换成为全局(替换找到的表达式的所有实例)。我还必须使用反斜杠转义/in ,因为它是正则表达式中的控制字符。<br />\

回答by ToddBFisher

Sam has a good solution, another one is:

Sam有一个很好的解决方案,另一个是:

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