在我阅读的有关此功能的书籍中,我似乎得到了相互矛盾的建议。 我想知道是否有人可以澄清。 例如 Nicholas Zakas 指出函数参数具有格式的签名 function(match, pos, originalText)(P139:Web 开发人员专业 JavaScript 第二版:Wrox)
他接着说,当正则表达式有一个匹配项时,函数将传递三个参数(如上)。当有多个捕获组时,每个匹配的字符串作为参数传入,最后两个位置是position和originalText...
然后我们来看看 Doug Crockfords,JavaScript:好的部分。 (P90): 他再次规定语法为 string(searcValue,replaceValue) searchValue 可以是一个正则表达式 - 非常匹配.. 如果 replaceValue 是一个函数,第一个参数是匹配的文本,第二个是捕获组 1,第三个是捕获组 2,依此类推。 这里有一个明显的区别。 (即没有位置参数)
我还查看了 Pro JavaScript 设计模式 (APress P152) 中的一个示例,该示例启动了整个交叉引用过程。这些人(Ross Harmes/Dustin Diaz)毫无帮助地指定了带有两个名为 a 和 b 的参数的 replaceValue 函数。 但它倾向于强化 Doug Crockford 描述的概念。
有人可以确认 Nicholas Zakas 的描述是否也是一个有效的选项吗?
最佳答案
Zakas 是正确的,倒数第二个和最后一个参数是pos
和originalText
。来自 ECMA-262 3rd和 5th版本(第 15.5.4.11 节):
If
replaceValue
is a function, then for each matched substring, call the function with the following m + 3 arguments. Argument 1 is the substring that matched. IfsearchValue
is a regular expression, the next m arguments are all of the captures in the MatchResult (see 15.10.2.1). Argument m + 2 is the offset within string where the match occurred, and argument m + 3 isstring
.
请注意 String.prototype.replace
是 ECMA-262 第三版中的新内容。 JScript 的 MSDN 文档和 JavaScript 的 MDC 文档均符合此规范。
关于JavaScript 字符串替换为正则表达式并作为参数运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4114080/