AS3 在将 String.replace() 与正则表达式一起使用时是否支持函数?



你能在ActionScript中替换文本的位置放置一个函数吗?

例如,您可以采取以下措施:

string = string.replace(/bw+b/g, "word");

并这样做:

string = string.replace(/bw+b/g, function(m){ 
   return /^[A-Z]/.test(m) ? "Word" : "word" 
});

我收到此错误:

ArgumentError: Error #1063: Argument count mismatch on Function/<anonymous>(). Expected 1, got 3.
    at String$/_replace()

我在这里找到了更多信息。

因此,虽然这在 JavaScript 中有效:

string = string.replace(/bw+b/g, function(m){ 
   return /^[A-Z]/.test(m) ? "Word" : "word" 
});

我们必须删除参数并使用适用于所有函数的参数对象,如下所示:

string = string.replace(/bw+b/g, function():String {
   var match:String = arguments[0];
   //var matchIndex:int = arguments[arguments.length-2];
   //var updatedString:String = arguments[arguments.length-1];
   return /^[A-Z]/.test(match) ? "Word" : "word" 
});

以下是有关这些参数的更多说明:

当您将函数指定为 repl 时,replace(( 方法会传递函数的以下参数:

  • 字符串的匹配部分。
  • 任何捕获的括号组匹配项都作为下一个参数提供。以这种方式传递的参数数量会有所不同取决于括号匹配项的数量。您可以确定通过检查参数的括号匹配数.长度 - 3在函数代码中。
  • 字符串中匹配开始的索引位置。
  • 完整的字符串。

最新更新